Perusing
Perusing

Reputation: 11

Advice needed to parse this JSON in .NET

Given the following JSON samples, what is the best way to parse this in c# .NET?

{"data":{"5":{"isDeleted":"false","day":"THU"}},"action":"edit"}
{"data":{"7":{"isDeleted":"false","name":"alex"}},"action":"edit"}
{"data":{"90":{"isDeleted":"true","job":"software"}},"action":"edit"}

I have looked into JSON serializing into an object but because the data could be different each time i can't map it directly to a model.

Upvotes: 0

Views: 64

Answers (2)

MD Zand
MD Zand

Reputation: 2605

You can deserialize the JSON into a dynamic object, which allows you to access the properties of the JSON object without having to define a specific model with JsonSerializer of System.Text.Json:

string jsonString = "{\"data\":{\"5\":{\"isDeleted\":\"false\",\"day\":\"THU\"}},\"action\":\"edit\"}";
dynamic jObject = JsonSerializer.Deserialize<dynamic>(jsonString);
string action = jObject .action;
dynamic data = jObject .data;
string isDeleted = data["5"].isDeleted;
string day = data["5"].day;

Upvotes: 0

zaitsman
zaitsman

Reputation: 9499

So the model for this could be

public class Record 
{
  public Dictionary<string, Dictionary<string, string>> Data { get; set; }
  public string Action { get; set; }
}

Upvotes: 1

Related Questions