3

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, the JSON serialization is structured like this:

[
  {
    "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).

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think this will work just fine. Thank you for the prompt response :)
Okay, thanks for that... I'll give that a shot before diving into the RegisterConverters business. Thanks Marc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.