C# JSON 自定义序列化 [英] C# JSON custom serialization
本文介绍了C# JSON 自定义序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法/库可以让我自定义类似于 GSON 自定义序列化程序的 JSON 序列化?
Is there a way/library that will allow me to customize JSON serialization similar to GSON custom serializers?
这是我想要得到的:
这个对象:KeyValuePair("Age",10) myAge
通常会像
我的年龄":{"Key": "年龄",价值":10}
虽然我希望它序列化为:"Age": 10.有什么想法吗?
whilst I want it to serialize like: "Age": 10 instead. Any ideas?
推荐答案
首先我建议使用 牛顿 json dll.
其次您需要为 KeyValuePair 创建自定义 JsonConverter,如下所示:
Second your need create custom JsonConverter for KeyValuePair like this:
public class PairConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(KeyValuePair<string, int>);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var item = (KeyValuePair<string, int>)value;
writer.WriteValue(item.Value);
writer.Flush();
}
}
然后为年龄"属性添加 JsonConverter 属性,如下所示:
And than add JsonConverter attribute for 'Age' property like this:
public class Persons
{
[JsonConverter(typeof(PairConverter))]
public KeyValuePair<string, int> Age { get; set; }
}
最后,用法示例:
var persons = new Persons()
{
Age = new KeyValuePair<string, int>("Age", 10)
};
var json = JsonConvert.SerializeObject(persons); // {Age:10}
这篇关于C# JSON 自定义序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文