Home > Software design >  How can I read each key values
How can I read each key values

Time:08-16

I am reading the cost value below

original data look like :-

 {
   "Key":"Cost",
   "Value":[
      {
         "Key":"a",
         "Value":5.25
      },
      {
         "Key":"b",
         "Value":0
      },
      {
         "Key":"c",
         "Value":5.25
      },
      {
         "Key":"d",
         "Value":0
      }
   ]
}

My expected result is I need to read a,b,c,d not data["Cost"].

How can I read each separately

CodePudding user response:

// Root myDeserializedClass = JsonSerializer.Deserialize<Root>(myJsonResponse);
//myDeserializedClass.Value will contain all key and value
public class Root
{
    [JsonPropertyName("Key")]
    public string Key { get; set; }

    [JsonPropertyName("Value")]
    public List<Value> Value { get; set; }
}

public class Value
{
    [JsonPropertyName("Key")]
    public string Key { get; set; }

    [JsonPropertyName("Value")]
    public double Value { get; set; }
}

classes generated through https://json2csharp.com/

CodePudding user response:

the easiest way would be to convert a json to a dictionary

var costs= JObject.Parse(json)["Value"]
                  .ToDictionary(j => (string) j["Key"], j=> (decimal) j["Value"] );

decimal c  = costs["c"]; //5.25

or using dynamic

var dict = JObject.Parse(json)["Value"]
                    .ToDictionary(j => (string)j["Key"], j => (object)j["Value"]);

dynamic costs = dict.Aggregate(new ExpandoObject() as IDictionary<string, object>,
                                (a, p) => { a.Add(p); return a; });
decimal c = costs.c;
  • Related