Search code examples
jsonasp.net-corejson-deserialization

How to deserialize list JSON using entity class?


I am getting a JSON in which it include list. Now I want to use only some property rather than all the properties. JSON

{ 
  "instance_pools" : [
      {
          "instance_pool_name":"pool1",
          "node_type_id":"standard",
          "azure_attributes":{
              "availability":"on"
           },
           "instance_pool_id":"poool2345",
           "status":{}
      },
      {
          "instance_pool_name":"pool1",
          "node_type_id":"normal",
          "azure_attributes":{
              "availability":"on"
           },
           "instance_pool_id":"poool2345",
           "status":{}
      },
      {
          "instance_pool_name":"pool1",
          "node_type_id":"high",
          "azure_attributes":{
              "availability":"on"
           },
           "instance_pool_id":"poool2345",
           "status":{}
      }
  ]
}

Now at .Net side, I only want instance_pool_name and corresponding instance_pool_id. I am new to .Net, Can somebody please help me with how to deserialize this complex JSON and use only some properties.

Thank you


Solution

  • You can create the classes as you want. You must not map all json properties into C# class' property. Therefore you can write the C# classes with the properties you need:

    public class InstancePoolCollection
    {
        public InstancePool[] instance_pools{get;set;}
    }
    
    
    public class InstancePool
    {
        public string instance_pool_id{get;set;}
        public string instance_pool_name{get;set;}
    }
    

    Deserializing using System.Text

    var obj = JsonSerializer.Deserialize<InstancePoolCollection>(jsonObj);
    

    Deserializing using Newtonsoft.Json

    var obj = JsonConvert.DeserializeObject<InstancePoolCollection>(jsonObj);
    

    Note: Your JSON was not conform. I have changed it.