How to dynamically change JSON records?

102 views Asked by At

I have a JSON string in the following structure:

"{'Country':'USA','City':'New York','Population':'8554554','Area':'545887','jsonArgs':'{\"BuildingsTypes\":\"Offices\"}','keywords':['keyword1','keyword2']}"

What I need to do is to update Area and BuildingsTypes values. I have tried to do the following:

string updatedJSON = String.Format("{'Country':'USA','City':'New York','Population':'8554554','Area':'{0}','jsonArgs':'{\"BuildingsTypes\":\"{1}\"}','keywords':['keyword1','keyword2']}", countryArea, buildingType);

However, I geting that structure is wrong, but if I use falowing as static it works. I also have tried to create is as dynamic object as the following:

string[] stringKeywords = new string[] {"keyword1", "keyword2"};

var jsonArgs = new
                {
                    featureTypes = buildingType

                };
var layerDescription = new
                {
                    Country = "USA",
                    City = "New York",
                    Population = "8554554",
                    Area = countryArea,
                    jsonArgs = jsonArgs,
                    keywords = stringKeywords

                };
string stringJSON = JsonConvert.SerializeObject(layerDescription);

By this I getting almost correct result:

"{'Country':'USA','City':'New York','Population':'8554554','Area':'545887','jsonArgs':{\"BuildingsTypes\":\"Offices\"},'keywords':['keyword1','keyword2']}"

What is missing here is single quotations around {\"BuildingsTypes\":\"Offices\"} do to this the other application to which I'm sending the string is not accepting it. How can I add dynamically the values or add the missing quotations? Thank you in advance.

2

There are 2 answers

0
Alexander Petrov On BEST ANSWER

If you want the extra quotes around the jsonArgs value, then you need to convert the object to a string. The easiest way to do this is to make an additional call to the serializer.

var args = new { featureTypes = buildingType };
var jsonArgs = JsonConvert.SerializeObject(args);
0
Ehtasham Bukhari On

If it is about the quotes like the rest just replace

stringJSON.Replace("\"", "'");