Home > Software design >  Required help in storing particular value from JSON to Dictionary using c#
Required help in storing particular value from JSON to Dictionary using c#

Time:06-24

I am barely new to c# world. I am able to resolve the below issue in Java world, but I am struggling with c#. could someone please help me on this.

Here is my input json file

JSON File Name - dBConfig.json

 {
  "parameterName1": "parameterValue1",
  "parameterName2": "parameterValue2",
  "parameterName3": [
    {
      "parameterName3Key": "Key1",
      "parameterName3Value": "Value1"
    },
    {
      "parameterName3Key": "Key2",
      "parameterName3Value": "Value2"
    }
  ]
}

Followed by .cs file

namespace Automation.Helpers
{
    public class RefVariables
    {
        public RefVariables(string datasetName)
        { 
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestData/DatabaseConfig");
            string filePath = Path.Combine(path, $"dBConfig.json");
            if (!File.Exists(filePath))
                throw new FileNotFoundException(filePath);

            string databaseConfigContents = File.ReadAllText(filePath);
            var data = (JObject)JsonConvert.DeserializeObject(databaseConfigContents);

            parameterName1 = data["parameterName1"].Value<string>();
            parameterName2 = data["parameterName2"].Value<string>();


            // code to get the parameterName3 array and store parameterName3Key value using loop & List & any other idea 

            parameterName3.Add("Ex: Key1, Key2 from Json....", "Ex: Value1 ,Value2 from json....");
        }

        public String parameterName1 { get; set; }
        public String parameterName2 { get; set; }

        // Source Database Names
        public Dictionary<string, string> parameterName3= new Dictionary<string, string>();
    }
}

I am able to read the direct key & value mapping but this array concept.

CodePudding user response:

You can first deserialize your JSON string into an object like this:

public class TheThing
{
    public string parameterName1 { get; set; }
    public string parameterName2 { get; set; }
    public Parametername3[] parameterName3 { get; set; }
}

public class Parametername3
{
    public string parameterName3Key { get; set; }
    public string parameterName3Value { get; set; }
}

and then use .ToDictionary:

var path = @"C:\dBConfig.json";
var jsonString = File.ReadAllText(path);
var theThing = JsonConvert.DeserializeObject<TheThing>(jsonString);
var outputDict = theThing.parameterName3.ToDictionary(x => x.parameterName3Key);

CodePudding user response:

you don't need any custom classes, try this

JObject data = JObject.Parse(databaseConfigContents);

    string parameterName1 = data["parameterName1"].Value<string>();
    string parameterName2 = data["parameterName2"].Value<string>();

    Dictionary<string,string> parameterName3 = ((JArray)data["parameterName3"])
                              .ToDictionary(v => (string) v["parameterName3Key"], v=>(string)v["parameterName3Value"]);
                              
  • Related