首页 新闻 会员 周边

使用json.net 如何只序列化类的部分属性

0
[已关闭问题] 关闭于 2018-01-30 20:35

JsonConvert.SerializeObject()方法可以把对象的所有属性序列化为json,但是现在我仅需要对部分属性序列化,查阅json.NET的相关文档后,发现有这么一段话:

By default a type's properties are serialized in opt-out mode. What that means is that all public fields and properties with getters are automatically serialized to JSON, and fields and properties that shouldn't be serialized are opted-out by placing JsonIgnoreAttribute on them. To serialize private members, the JsonPropertyAttribute can be placed on private fields and properties.

也就是说,默认情况下所有属性均会被序列化,但是可以使用JsonIgnoreAttribute排除部分不需要序列化的属性。然后查阅JsonIgnoreAttribute的说明,发现

Excludes a field or property from serialization.

The NonSerializedAttribute can be used as a substitute for JsonIgnoreAttribute.

也就是说,JsonIgnoreAttribute现在又弃用了,改用NonSerializedAttribute了。然后我又试着引入NonSerializedAttribute

 [AttributeUsage(AttributeTargets.Field, Inherited = false)]
    public sealed class NonSerializedAttribute : Attribute
    {
        public extern NonSerializedAttribute();
    }

    [Serializable]
    public class A
    {
        string name;
        int age;
        ......
     }

能通过编译,但是最后在执行时会报

System.TypeLoadException:“未能从程序集“XXX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中加载类型“XXX.NonSerializedAttribute”,因为方法“.ctor”没有实现(没有 RVA)。”

请问这是什么原因,方便解决吗?如果没有,还有其他替代方案吗?

谢谢

Windroid的主页 Windroid | 菜鸟二级 | 园豆:201
提问于:2018-01-29 17:50
< >
分享
所有回答(4)
1

在不需要序列化的属性上标注 “[JsonIgnore]”。

数据酷软件 | 园豆:130 (初学一级) | 2018-01-29 17:55

打上[JsonIgnore]标记后可以运行了,但是依然是所有的属性都被序列化了

支持(0) 反对(0) Windroid | 园豆:201 (菜鸟二级) | 2018-01-29 18:04
0

需要这么麻烦吗?重新搞个匿名类,放你需要序列化的属性

~冰 | 园豆:509 (小虾三级) | 2018-01-30 15:39
0

折腾了一天自己解决了。其实很简单。

需要用到两个类标记:

[JsonObject(Newtonsoft.Json.MemberSerialization.OptIn)]:默认不序列化,需要序列化的属性使用[JsonProperty]标记

[JsonObject(Newtonsoft.Json.MemberSerialization.OptOut)]:默认序列化,不需要序列化的属性使用[JsonIgnore]标记

例如,一个Stdudent类有name、age、address三个属性,如果只想序列化name和age可以这么定义

[JsonObject(Newtonsoft.Json.MemberSerialization.OptIn)]
class Student{
[JsonProperty]
string name;
[JsonProperty]
int age; string address; }

或者

[JsonObject(Newtonsoft.Json.MemberSerialization.OptOut)]
class Student{
string name;
int age;
[JsonProperty]
string address;
}
Windroid | 园豆:201 (菜鸟二级) | 2018-01-30 20:34
0

我感觉你弄的比较麻烦,我也是直接在属性上标注 [JsonIgnore] 在序列化时进行忽略,

我之前也写过一篇跟涉及序列化的文章,就是直接使用 [JsonIgnore],并且有效果图:

http://www.cnblogs.com/liqingwen/p/7483392.html

反骨仔 | 园豆:444 (菜鸟二级) | 2018-03-20 11:15
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册