json.Net保存到文件

时间:2015-06-01 07:27:23

标签: c# json json.net

我有一个用于保存到文件排序的脚本,但我无法将其编码保存到输入:如下所示

{
    "entry": [
        { "Name": "John" },
        { "Name": "Anna" },
        { "Name": "Peter" }
    ]
}

我使用json.Net,下面的代码需要添加到条目:name

 string json = JsonConvert.SerializeObject(results, Formatting.Indented);
 string path = @"C:\inetpub\wwwroot\JSON\json.Net\results.json";

 if (!File.Exists(path))
 {
     File.WriteAllText(path, json);
 }
 else
 {
     File.AppendAllText(path, json);
 }

我还没能找到任何好的json代码样本,欢呼保罗

1 个答案:

答案 0 :(得分:1)

我是这样管理的!

  UserInfo results = new UserInfo
    {
        Name = Request["name"],

    };

    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    JsonWriter jsonWriter = new JsonTextWriter(sw);
    jsonWriter.Formatting = Formatting.Indented;
    jsonWriter.WriteStartObject();
    jsonWriter.WritePropertyName("Name");
    jsonWriter.WriteValue(results.Name);
    jsonWriter.WriteEndObject();

    string json = sw.ToString();
    jsonWriter.Close();
    sw.Close();

    string path = @"C:\inetpub\wwwroot\JSON\json.Net\results.json";

    if (!File.Exists(path))
    {
        File.WriteAllText(path, json);
    }
    else
    {
        File.AppendAllText(path, json);
    }

}

// create a class object to hold the JSON value
public class UserInfo
{
    public string Name { get; set; }

}