简体   繁体   English

将对象数组作为一个对象序列化,并在C#中使用JSON序列化程序为每个对象指定一个命名属性

[英]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方便的例子,但你应该能够:

  • write a wrapper class that encapsulated the list/array 编写一个封装列表/数组的包装类
  • use the JavaScriptSerializer class 使用JavaScriptSerializer类
  • after creating the serializer, associate the wrapper-type with a custom serializer 创建序列化程序后,将包装类型与自定义序列化程序相关联
  • in the custom serializer, iterate over the data, adding a key to the dictionary per-item, ie data.Add("item"+i,list[i]); 在自定义序列化程序中,迭代数据,向每个项目的字典添加一个键,即data.Add(“item”+ i,list [i]);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM