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

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


You might did that just putting the data into a dictionary is enough for 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:

  • write a wrapper class that encapsulated the list/array
  • use the JavaScriptSerializer class
  • 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, i.e. 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

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.