Home > other >  C# Parse a dynamic JSON JToken to a List
C# Parse a dynamic JSON JToken to a List

Time:11-11

Can we parse a dynamic JSON to a List of Object List<DiffModel>

public class DiffModel 
{
  public string Property { get; set; }
  public string OldValue { get; set; }
  public string NewValue { get; set; }
} 

The JSON is generated with the help of a library which helps to compare 2 JSON objects and find out the differences. The differences are getting stored as a JToken

Sample JSON JToken value generated with help of JToken patch = jdp.Diff(left, right) method

{
  "Id": [
    78485,
    0
  ],
  "ContactId": [
    767304,
    0
  ],
  "TextValue": [
    "text value",
    "text14"
  ],
  "PostCode": [
    null
  ]
}

From the JSON the value of first item in the object is

DiffModel [0] =  Property ="id" OldValue="78485" NewValue="0"
DiffModel [1] =  Property ="contactId" OldValue="767304" NewValue="0"
DiffModel [2] =  Property ="TextValue" OldValue="text value" NewValue="text14"
DiffModel [3] =  Property ="PostCode" OldValue= null NewValue=null

Can we navigate between the properties of dynamic JSON and build a similar model

CodePudding user response:

You can define a data model like this:

struct DiffModel
{
    public string Property { get; init; }
    public object OldModel { get; init; }
    public object NewModel { get; init; }
}

I've used struct but you can use class, record whatever you prefer.

Then you can convert the JToken to a Dictionary<string, object[]>.

  • The key will be the property name
  • the value will be the property values
var rawModel = patch.ToObject<Dictionary<string, object[]>>();

Finally, all you need is a mapping between the DiffModel and the KeyValuePair<string, object[]>:

var diffModels = rawModel
    .Select(pair => new DiffModel
    {
        Property = pair.Key,
        OldModel = pair.Value.First(),
        NewModel = pair.Value.Last(),
    }).ToArray();
  • Related