读取json文件并使用JSON.NET进行更改

时间:2014-10-14 22:21:16

标签: c# json winforms json.net

JSON对我来说真的很新。如何使用JSON.NET将键值对添加到已创建的json文件中?

看起来像这样:

{
"data": {
    "subData1": {
        "key1":"value1",
        "key2":"value2",
        "key3":"value3"
    },
    "subdata2": {
        "key4":"value4",
        "key5":"value5",
        "key6":"value6"
    }
}
"key7":"value7",
"key8":"value8"     
}

假设我想将其更改为以下示例:

{
"data": {
    "subData1": {
        "key1":"value1",
        "key2":"value2",
        "key3":"value3"
    },
    "subdata2": {
        "key4":"value4",
        "key5":"value5",
        "key6":"value6"
    },
    "newSubData": {
        "myKey1":"myVal1",
        "myKey2":"myVal2",
        "myKey3":"myVal3"
    }
}
"key7":"anotherValChangeByMe",
"key8":"value8"     
}

我是否需要将整个JSON文件读入动态内容,然后以某种方式更改/添加我需要的内容?

2 个答案:

答案 0 :(得分:3)

您可以将JSON解析为JObject,通过LINQ-to-JSON API对其进行操作,然后从JObject获取更新的JSON字符串。

例如:

string json = @"
{
    ""data"": {
        ""subData1"": {
            ""key1"": ""value1"",
            ""key2"": ""value2"",
            ""key3"": ""value3""
        },
        ""subdata2"": {
            ""key4"": ""value4"",
            ""key5"": ""value5"",
            ""key6"": ""value6""
        }
    },
    ""key7"": ""value7"",
    ""key8"": ""value8""
}";

JObject root = JObject.Parse(json);
JObject data = (JObject)root["data"];
JObject newSubData = new JObject();
newSubData.Add("myKey1", "myValue1");
newSubData.Add("myKey2", "myValue2");
newSubData.Add("myKey3", "myValue3");
data.Add("newSubData", newSubData);
root["key7"] = "anotherValChangeByMe";

Console.WriteLine(root.ToString());

输出:

{
  "data": {
    "subData1": {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
    },
    "subdata2": {
      "key4": "value4",
      "key5": "value5",
      "key6": "value6"
    },
    "newSubData": {
      "myKey1": "myValue1",
      "myKey2": "myValue2",
      "myKey3": "myValue3"
    }
  },
  "key7": "anotherValChangeByMe",
  "key8": "value8"
}

答案 1 :(得分:1)

JSON最终只是一个字符串。如果您在服务器端工作,那么除非您想尝试自己解析JSON,否则最简单的方法是使用JSON.NET将其反序列化为其本机对象模型。当然,您也可以使用JSON.parse()在客户端执行此操作,并在那里添加值。