4

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"
}
Sanju Rao
  • 331
  • 1
  • 6
  • 25

1 Answers1

5

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;
        }
Palanikumar
  • 6,940
  • 4
  • 40
  • 51