Friday 15 May 2015

c# - Reading a json file and change it with JSON.NET -



c# - Reading a json file and change it with JSON.NET -

json new me. how can utilize json.net add together key value pair created json file?

it looks this:

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

say illustration want alter following:

{ "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" }

do need read whole json file dynamic, , alter / add together things need somehow ?

you can parse json jobject, manipulate via linq-to-json api, updated json string jobject.

for example:

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 info = (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());

output:

{ "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" }

c# json winforms json.net

No comments:

Post a Comment