指定要使用JSON序列化的字段

时间:2013-08-14 02:13:06

标签: c# json serialization

这是关于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对象创建了customizeAttribute,如下所示:

    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,
       }
    }

1 个答案:

答案 0 :(得分: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类,将Book实例映射到控制器中的BookViewModel实例并传递视图模型而不是模型进行查看(serilalize到json)。