如何动态更改JSON记录?

问题描述

我具有以下结构的JSON字符串:

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

我需要做的是更新 Area BuildingsTypes 值。 我尝试执行以下操作:

string updatedJSON = String.Format("{'Country':'USA','Area':'{0}','jsonArgs':'{\"BuildingsTypes\":\"{1}\"}','keyword2']}",countryArea,buildingType);

但是,我得到的结构是错误的,但是如果我使用falow作为静态,它将起作用。 我也曾尝试创建如下的动态对象:

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);

通过这种方式,我得到几乎正确的结果:

"{'Country':'USA','jsonArgs':{\"BuildingsTypes\":\"Offices\"},'keyword2']}"

这里缺少的是{\"BuildingsTypes\":\"Offices\"}周围的单引号,对此我要向其发送字符串的其他应用程序不接受。 如何动态添加值或添加缺少的报价? 预先谢谢你。

解决方法

如果要在jsonArgs值周围加上引号,则需要将对象转换为字符串。最简单的方法是再次调用序列化程序。

var args = new { featureTypes = buildingType };
var jsonArgs = JsonConvert.SerializeObject(args);
,

如果与其他引号一样,只需替换

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...