dmxyler
dmxyler

Reputation: 79

Dynamic json property deserialize

I'm having difficulties figuring out how to deserialize a json, that has a dynamic property (for example - UserRequest::567) the property name can be any value and the UserRequest object contains other json properties that are of interest to me

I tired writing a class and I don't know what to do with that property. What are the best practices for coping with a problem like this?

{
    "objects": {
        "UserRequest::567": {
            "code": 0,
            "message": "created",
            "class": "UserRequest",
            "key": "567",
            "fields": {
                "ref": "R-000567",
                "org_id": "4"
            }
        }
    }
}

enter image description here

The question is what are the best practices to read through this kind of a json string?

Thank you

Upvotes: 1

Views: 548

Answers (1)

jaabh
jaabh

Reputation: 1004

To Deserialize this using Newtonsoft.Json, here are the classes:

public class CreateRequest
{
    public long code { get;set; }
    public string message { get; set; }

    [JsonProperty("class")]
    public string class1 { get; set; }

    public string key { get; set; }
    public Fields fields { get; set; }
}

public class Fields
{
    [JsonProperty("ref")]
    public string refe { get; set; }
    public string org_id { get; set; }
}

public class Root
{
    public Dictionary<string, CreateRequest> objects { get; set; }
    //The 'string' key in the dictionary is the 'UserRequest::567'
}

Then to Deserialize use:

var x = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(jsonObject).objects.Values;

Upvotes: 1

Related Questions