Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deserialize this JSON?

How do I deserialize the following JSON with Web API (JSON.Net)?:

{
    "action": "edit",
    "table": "MainView",
    "id": "row_1377",
    "_group_id": "999",
    "data": {
        "ROTATION": "1", // This name/val can change
        "EQUIPMENT": [{
            "id": "6"
        },
        {
            "id": "8"
        }],
        "NOTES": ""
    }
}

The values in data represent columns and can change, so I can't make a set-in-stone object with e.g. a string named "NOTES" as in json.net deserialize string to nested class.

Notice EQUIPMENT contains multiple values. When it was previously just a "string:string" like NOTES, this JSON deserialized data into a Dictionary<string, string>, but now I need it to behave like its own dictionary. My last attempt was to deserialize into the following type:

public class EditorSubmissionJoined
{
    public string _group_id { get; set; }
    public string action { get; set; }
    public string table { get; set; }
    public string id { get; set; }
    // "public" added below due to mistake noticed by Maggie Ying
    public Dictionary<string, object> data { get; set; } // Trouble
}

I was hoping that the object could contain anything in data whether a KeyValuePair (like NOTES) or a dictionary (like EQUIPMENT).

I've also tried Dictionary<string, ICollection<Object>>, Object, and even ICollection<Dictionary<string, Object>>.

The problem is that my controller always gets EditorSubmissionJoined with nothing but null values:

public void Put(EditorSubmissionJoined ajaxSubmission) {
    // ajaxSubmission has only NULL values
}
like image 417
Charles Burns Avatar asked Jul 18 '26 14:07

Charles Burns


2 Answers

Try setting your 'data' property to public and your JSON should be able to model bind correctly.

like image 122
Maggie Ying Avatar answered Jul 21 '26 04:07

Maggie Ying


There's a few ways you can do it. One way is to simply use a JObject and access the fields by name e.g. : jsonObject["data"]["ROTATION"]. You can "deserialize" that with JObject.Parse and just "parse" the JSON text into a JObject.

Alternatively you can write your own JsonConverter and tell JSON.net to use that converter when deserializing a specific type (e.g. JsonConverterAttribute). This requires parsing parts of the JSON text manually, in the ReadJson override, and really depends on what data you expect.

You can also use the dynamic approach that Preston commented on.

Which approach you pick depends on how strongly-typed you want things to be.

like image 45
Peter Ritchie Avatar answered Jul 21 '26 02:07

Peter Ritchie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!