如何在C#中将查询写入JSON文件

时间:2016-08-25 06:29:53

标签: c# json

我必须在我的C#项目中编辑我的JSON文件,但是我遇到了一些问题。而且,我正在使用json.net

我的JSON文件deathGod.json:

{
  "toKillList": [
    {
      "Name": "John",
      "dieWith": "eat hot dog",
      "Date": "date",
      "State": "state"
    },
    {
      "Name": "peter",
      "dieWith": "swim",
      "Date": "date",
      "State": "state"
    }
  ]
}

我的编码:

string path = @"\users\deathGod\documents\visual studio 2012\Projects\killApp\killApp\deathGod.json";
string jsonData = File.ReadAllText(path);

dynamic result = JsonConvert.DeserializeObject(jsonData);
JArray items = (JArray)result["toKillList"];

问题:

我需要向JArray添加一个查询,然后将Jarray添加到JObject。但是,引号和换行符会杀死我的文件。

代码:

string element = @"{'Name':’may’,
                     ‘Path’:’driving’,
                     ‘Date’:’date’, 
                     ‘State’:’state’}";

JValue value = new JValue(element);
items .Add(value);
//JArray => JObject => json file

结果:

{
  "toKillList": [
        {
          "Name": "John",
          "dieWith": "eat hot dog",
          "Date": "date",
          "State": "state"
        },
        {
          "Name": "peter",
          "dieWith": "swim",
          "Date": "date",
          "State": "state"
    },
    "{'Name':’may’, \r\n‘Path’:’driving’,\r\n ‘Date’:’date’,\r\n ‘State’:’state’\r\n}"
  ]
}

任何想法?

2 个答案:

答案 0 :(得分:1)

您应该构建JObject而不是JValue

var element = JObject.FromObject(new
{
    Name = "may",
    Path = "driving",
    Date = "date",
    State = "state"
});
items.Add(element);

答案 1 :(得分:0)

如果要将字符串转换为JSon,请首先将替换为'。然后使用以下代码:

var element = @"{'Name':'may','Path':'driving', 'Date':'date', 'State':'state'}";

var value = (JToken)JsonConvert.DeserializeObject(element);
items.Add(value);

var res = JsonConvert.SerializeObject(result);

最终结果是:

{
  "toKillList":[
     {"Name":"John","dieWith":"eat hot dog","Date":"date","State":"state"},
     {"Name":"peter","dieWith":"swim","Date":"date","State":"state"},
     {"Name":"may","Path":"driving","Date":"date","State":"state"}
  ]
}