1.通常情况下,使用[JsonProperty] 属性就可以实现需求。
2.有些情况下,由于开发者无法修改dll 中的文件,因此无法添加任何属性。此时,可以自定义序列化设置,从而强制序列化私有字段。
第一步,创建自定义解析类,并重写CreateProperties 方法:
public class ForceJSONSerializePrivatesResolver :
Newtonsoft.Json.Serialization.DefaultContractResolver
{
protected override IList CreateProperties
(System.Type type, MemberSerialization memberSerialization)
{
var props = type.GetProperties(System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance);
List jsonProps =
new List();
foreach (var prop in props)
{
jsonProps.Add(base.CreateProperty(prop, memberSerialization));
}
foreach (var field in type.GetFields(System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance))
{
jsonProps.Add(base.CreateProperty(field, memberSerialization));
}
jsonProps.ForEach(p => { p.Writable = true; p.Readable = true; });
return jsonProps;
}
}
第二步,序列化和反序列化时传入自定义解析类
var settings = new JsonSerializerSettings() {
ContractResolver = new ForceJSONSerializePrivatesResolver() };
stringYourObjectJsonString= JsonConvert.SerializeObject(YourObject, settings);
JsonConvert.DeserializeObject<YourObject>(YourObjectJsonString, settings);
网友评论