这是关于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,
}
}