简体   繁体   中英

deserializing an specific json string

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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