Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the Json data without knowing the Key value

I have a json data which comes as the input string. Now I need to update the existing Json data with the input Json data. In my case, I want to go through each key and match with existing Json data and then update the value of that Key with input Json data.

Code to retrive the existing data

var existingJSon = ProductRepository.ListOfProd.Cast<JArray>().Where(x => x["ProdId"].ToString() == id.ToString());

After retrieving the data my existingJson will look like below.

{
    ProdId:"1",
    Title:"C#",
    Author:"Jeffy",
    Publisher:"XYZ",
    Category:"Microsoft"
    }

Now I need to loop through every key that comes as the input and match to the existing Json key and update the value of that key.

Input and after updating it should look like this:

{
ProdId:"1",
Title:"C#",
Author:"Jeffy",
Publisher:"abcd",
Category:"Microsfot Basic .Net Development Kit"
}
like image 437
Sanju Rao Avatar asked Sep 11 '25 23:09

Sanju Rao


1 Answers

See if this helps you, We can use Newtonsoft to deserialize unknown types and loop the keys and values.

string json = "{ProdId:\"1\",Title:\"C#\",Author:\"Jeffy\",Publisher:\"XYZ\",Category:\"Microsoft\"}";
        JObject obj = JsonConvert.DeserializeObject < JObject>(json);
        var properties = obj.Properties();
        foreach (var prop in properties)
        {
            string key = prop.Name;
            object value = prop.Value;
        }
like image 171
Palanikumar Avatar answered Sep 13 '25 12:09

Palanikumar