我将Windows通用应用程序中的C#对象序列化为JSON,使用custom Converter命名对象中description
字符串后面的节点。而不是
{
"description":"upper-left",
"value":23
},
{
"description":"upper-right",
"value":24
}
我得到了
[
{
"upper-left":23
},
{
"upper-right":24
}
]
这适用于我,使用转换器的改编版本。但是,我想在单个节点中收集这些键:值对,如下所示:
{
"upper-left":23,
"upper-right":24
}
我怎样才能做到这一点?
答案 0 :(得分:0)
I created a custom converter for this -
internal class MyObjectJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dataList = value as List<RootObject>;
writer.WriteStartObject();
foreach (var data in dataList)
{
writer.WritePropertyName(data.description);
writer.WriteValue(data.value);
}
writer.WriteEndObject();
}
}
where -
public class RootObject
{
public string description { get; set; }
public int value { get; set; }
}
var s = JsonConvert.SerializeObject(new List<RootObject> {
new RootObject
{
description = "upper-left",
value = 23
},
new RootObject
{
description = "upper-right",
value = 24
}
}, jss);