skip to Main Content

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.

2

Answers


  1. So the model for this could be

    public class Record 
    {
      public Dictionary<string, Dictionary<string, string>> Data { get; set; }
      public string Action { get; set; }
    }
    
    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search