[英]Serialize array of objects as one object with a named property for each object in C# with JSON serializer
I have a List that, when serialized as JSON gives me an array of objects. 我有一个List,当序列化为JSON时,会给我一个对象数组。 However, I need the serialized version to be structured as follows:
但是,我需要将序列化版本的结构如下:
{
"item3":{
"id":3,
"name":"monkey"
},
"item4":{
"id":4,
"name":"turtle"
}
}
Currently, the JSON serialization is structured like this: 目前,JSON序列化的结构如下:
[
{
"id":3,
"name":"monkey"
},
{
"id":4,
"name":"turtle"
}
]
My goal is to be able to reference the array by item ID instead of numeric index (ie. arr["item3"].name instead of arr[0].name). 我的目标是能够按项ID而不是数字索引引用数组(即.arr [“item3”]。name而不是arr [0] .name)。
You might did that just putting the data into a dictionary is enough for JaveScripySerializer: 您可能只是将数据放入字典就足以让JaveScripySerializer:
var dict = list.ToDictionary(
item => "item" + item.id);
(and serialize dict) (并序列化字典)
If not: 如果不:
I don't have a PC handy for an example, but you should be able to: 我没有一个PC方便的例子,但你应该能够:
You associate custom maps via RegisterConverters: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.registerconverters.aspx 您通过RegisterConverters关联自定义地图: http : //msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.registerconverters.aspx
Note you don't need to write a deserialize unless you need that too. 请注意,除非您需要,否则不需要编写反序列化。
If you get stuck, I'll try to ad an example later. 如果您遇到困难,我会稍后尝试举例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.