1

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

5
  • You are on the right path, have you ever tried to use NewtonJson to deserialize your son object? Commented Aug 20, 2020 at 12:52
  • I have tried to serialize the whole json var createRequest = CreateRequest.FromJson(jsonString) But how do i dynamically get the UserRequest property name? It can be any name. For example - UserRequest::567, UserRequest::568 and so on. Commented Aug 20, 2020 at 12:54
  • are you talking about to deserialize a dynamic json string? Commented Aug 20, 2020 at 12:57
  • Yes. How for example i should read the code/message and other properties if my UserRequest is dynamic? Commented Aug 20, 2020 at 12:58
  • 1
    Use Dictionary. Commented Aug 20, 2020 at 14:52

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.