0

I can't deserialize following json string because the root element doesn't have key name. only a numeric value. I use Json.Net

{"41":{"entity_id":"41","status":"pending"},"42":{"entity_id":"42","status":"canceled"}}

this is a response from Magento REST Api. I can get the response in xml, But I can't deserialize using xml response too. there are two date_item nodes in two different child elements.

Reza Abolfathi
  • 3,061
  • 2
  • 18
  • 14
  • 2
    possible duplicate of [How can I parse a JSON string that would cause illegal C# identifiers?](http://stackoverflow.com/questions/24536533/how-can-i-parse-a-json-string-that-would-cause-illegal-c-sharp-identifiers) – Brian Rogers Jul 15 '14 at 12:55
  • ok my answer got deleted by some moderator but here the original link that was accepted as answer just in case someone else is interested: http://stackoverflow.com/questions/21752345/deserializing-json-that-has-an-int-as-a-key-in-c-sharp – Eleasar Jul 15 '14 at 21:27

1 Answers1

-1

You can use some attributes to help in the deserialization. For example:

[DataContract]
public class YourClass
{
    [DataMember(Name = "41")]
    public YourEntity Property41
    {
        get;
        set;
    }
}

[DataContract]    
public class Entity 
{
   [DataMember(Name = "entity_id")]
   public int EntityID { get; set; }

}

These attributes works with the default serializer:

    public static T DeserializeJson<T>(string objectInJson)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
        return (T)serializer.ReadObject(JsonSerializer.StringToStream(objectInJson));
    }

You can invoke it with DeserializeJson(jsonString)

Eric Lemes
  • 561
  • 3
  • 10
  • 2
    This is not a good solution here. The numeric key represents an ID, which will vary. The correct solution is to use a Dictionary. See the question linked in the comments. – Brian Rogers Jul 15 '14 at 16:28