Home > Blockchain >  Convert Json response into a Dictionary (Key value pairs) using C#
Convert Json response into a Dictionary (Key value pairs) using C#

Time:04-22

I have something like this

{
  "WellContactInfo": {
    "Customer": "Wintershall",
    "RigName": "Deepsea Aberdeen",
    "WellId": null
  }
}

I want to convert it into something like this

{
  "WellContactInfo": {
      {
          "name" : "Customer",
          "value" : "Wintershall"
      },
      {
        "name": "RigName",
      "value" : "Deepsea Aberdeen"
      },
      {
        "name": "WellId",
      "value" : null
      }
  }
}

I have a model with name WellContactInfo and values are assigned to the properties in it. Please suggest me a way on how to achieve the same. Please let me know if you need anymore information on this.

Note: The above Json is a sample and I have Json with multiple classes in it.

CodePudding user response:

You can deserialize the property WellContactInfo in your above example into a Dictionary<string, string> without adjustments using either System.Text.Json or Newtonsoft.Json.

An example using System.Text.Json:

using System.Text.Json;

var json = "{ \"WellContactInfo\": { \"Customer\": \"Wintershall\", \"RigName\": \"Deepsea Aberdeen\", \"WellId\": null } }";
var result = JsonSerializer.Deserialize<MyContact>(json);
public class MyContact
{
    public Dictionary<string, string> WellContactInfo { get; set; }
}

CodePudding user response:

try this

    var jsonParsed = JObject.Parse(json);

    WellContactInfoClass wellContactInfo = new WellContactInfoClass
    {
        WellContactInfo = ((JObject)jsonParsed["WellContactInfo"]).Properties()
                                   .Select(v => new KeyValuePair<string, string>(v.Name, (string)v.Value)).ToList()
    };

    public class WellContactInfoClass
    {
        public List<KeyValuePair<string, string>> WellContactInfo { get; set; }
    }
  • Related