1

这是关于json序列化的。情况如下:

public class Book
{       
    public string BookName { get; set; }
    public decimal BookPrice { get; set; }       
    public string AuthorName { get; set; }
    public int AuthorAge { get; set; }
    public string AuthorCountry { get; set; }
}

public class MyBag{
   public string owner {get; set;}
   public Book math_Book{get; set;}

}

Book 有几个字段,但并非所有字段都需要序列化。例如,我只想知道 BookName 和 BookPrice。我想指定字段名称并自定义 jsonPropertyAttribute。像这样:

 public class MyBag{
   public string owner {get; set;}
   [JsonProperty(serializedFields("BookName", "BookPrice"))]
   public Book math_Book{get; set;}
}

Json 是否具有自定义 JsonPropertyAttribute 的功能?或者我该怎么做才能完成这项工作?

由于我没有找到如何创建自定义 JsonPropertyAttribute,所以我为 Csharp 对象创建了自定义属性,如下所示:</p>

    public class SerializedFieldsAttribute : Attribute
{
    private IList<string> _serializedFields = new List<string>();
    public SerializedFieldsAttribute(string[] fields)
    {
        _serializedFields = fields;
    }

    public IList<string> GetFields()
    {
        return _serializedFields;
    }

}

 public class MyBag
{
    public String Owner { get; set; }
    [SerializedFieldsAttribute(new string[] { "BookName", "BookPrice" })]
    public Book MyBook { get; set; }
}

现在我可以得到 SerializedFieldsAttribute,但是我该怎么做

var book = new Book
            {
                BookName = "Yu Wen",
                BookPrice = 56,
                AuthorName = "Li QingZhao",
                AuthorAge = 28,
                AuthorCountry = "Song"
            };
        var bag = new MyBag
            {
                Owner = "shoren",
                MyBook = book
            };

    {
       "Owner": "shoren",
       "MyBook": {
            "BookName": "Yu Wen",
            "BookPrice": 56.0,
       }
    }
4

1 回答 1

2

试试ScriptIgnoreAttribute

public class Book
{       
    public string BookName { get; set; }
    public decimal BookPrice { get; set; }       

    [ScriptIgnore]
    public string AuthorName { get; set; }

    [ScriptIgnore]
    public int AuthorAge { get; set; }

    [ScriptIgnore] 
    public string AuthorCountry { get; set; }
}

BookViewModel更合适的解决方案是仅使用您需要的两个字段创建类,将您的实例映射BookBookViewModel控制器中的实例,并将视图模型而不是模型传递给视图(序列化为 json)。

于 2013-08-16T03:58:31.140 回答