Serialize an array of objects as one object with a named property for each object in C # using a JSON serializer

I have a List that, when serialized as JSON, gives me an array of objects. However, I need the serialized version to be structured as follows:

{
  "item3":{
    "id":3,
    "name":"monkey"
  },
  "item4":{
    "id":4,
    "name":"turtle"
  }
}

Currently, JSON serialization is structured as follows:

[
  {
    "id":3,
    "name":"monkey"
  },
  {
    "id":4,
    "name":"turtle"
  }
]

My goal is to be able to refer to an array by element identifier instead of a numerical index (ie arr ["item3"]. Name instead of arr [0] .name).

+3
source share
1 answer

, JaveScripySerializer:

var dict = list.ToDictionary(
    item => "item" + item.id);

( dict)

:

, :

  • , /
  • JavaScriptSerializer
  • -
  • , , , .. data.Add( "item" + i, list [i]);

RegisterConverters: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.registerconverters.aspx

, , .

, .

+2
source

Source: https://habr.com/ru/post/1778361/


All Articles