Newtonsoft.Json序列化怎么忽略只读?
以下是 class 代码
public string a { get; }
public string b { get; set; }
public string c;
以下是方法代码
jss ??= new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, //忽略循环引用 NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore, }; string str = JsonConvert.SerializeObject(obj, jss); return str;
我在序列化的时候发现 a 也被序列化了, 但是我是要把这个用于游戏存档, 要越小越好 (不压缩string)
我只想让 b, c 被序列化应该怎么弄
要求是不能修改 abc 的类, 所以没法加 [JsonIgnore] 之类的
这个功能,目前在net自己的System.Text.Json是已经默认支持的,jsonoption里就有控制
如果是Newton的库,我们需要自己实现他
我写了一个demo
sonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new WritablePropertiesOnlyResolver()
};
var obj = new test() { b = "b", c = "c" };
var str = JsonConvert.SerializeObject(obj, settings);
Console.ReadKey();
//这个就是只提取可写属性扩展
class WritablePropertiesOnlyResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
return props.Where(p => p.Writable).ToList();
}
}
class test
{
public string a { get; }
public string b{ get; set; }
public string c;
}