C#在json中编辑一些参数但保存未触及的参数

时间:2016-06-02 10:39:54

标签: c# json

我有一个像这样的JSON字符串:

{
    "param1": "value1",
    "param2": "value2",
    "param3": "value3",
    "somearray1": {
        "inarrparam1": "inarrvalue1",
        "inarrparam2": "inarrvalue2"
    },
    "param4": "value4",
    "somearray2": {
        "inarrparam3": "inarrvalue3",
        "inarrparam4": "inarrvalue4"
    }
}

在我的JSON字符串中有更多参数和数组。 我想编辑JSON字符串值,例如value1value3inarrvalue1。 然后,我需要保存已编辑的字符串,其中包含所有参数和值,其顺序与字符串的顺序相同或不同。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

实现它的一种方法是将json反序列化为类型化的C#对象,编辑属性并将其序列化为json -

var obj = JsonConvert.DeserializeObject<RootObject>("json String");
obj.param1 = "new Value1";
obj.param3 = "new Value3";
obj.somearray1.inarrparam1 = "new inarrvalue1";

var jsonString = JsonConvert.SerializeObject(obj);

其中RootObject是最顶级的父类型。

<强>输出

{
  "param1": "new Value1",
  "param2": "value2",
  "param3": "new Value3",
  "somearray1": {
    "inarrparam1": "new inarrvalue1",
    "inarrparam2": "inarrvalue2"
  },
  "param4": "value4",
  "somearray2": {
    "inarrparam3": "inarrvalue3",
    "inarrparam4": "inarrvalue4"
  }
}

答案 1 :(得分:0)

你在寻找类似的东西

&#13;
&#13;
var data = {
  "param1": "value1",
  "param2": "value2",
  "param3": "value3",
  "somearray1": {
    "inarrparam1": "inarrvalue1",
    "inarrparam2": "inarrvalue2"
  },
  "param4": "value4",
  "somearray2": {
    "inarrparam3": "inarrvalue3",
    "inarrparam4": "inarrvalue4"
  }
};

data.param1 = 'newValue1';
data.somearray1.inarrparam1 = 'newInarrvalue1';
console.log(data);
&#13;
&#13;
&#13;

修改

如果您想使用json string更新此C#,只需使用string.replace()功能进行更新。