0

我一直在使用 Json.NET 将内存中的对象序列化为 json。当我调用以下代码行时:

        string json = JsonConvert.SerializeObject(template, Formatting.Indented);

        System.IO.File.WriteAllText(file, json);

我在文本文件中得到以下内容:

{
  "template": {
    "title": "_platform",
    "description": "Platform",
    "queries": [
      {
        "query": "// *******************************\n// -- Remove  from DurationWindow at the end  \n// *******************************\t\n"
      }
    ],
    "metadata": ""
  }
}

查询是我从数据库中提取的一个对象,它有一个字符串值。当我使用 xml 并写入文件(使用 XDocument)时,字符串中的新行(以及 \t)被正确地解析为文件中的制表符和新行。使用 json.Net 是否可以在此处获得相同的效果?

4

1 回答 1

0

The line-break and tab chars are not valid in JSON values, and JSON.net won't render \t and \n into tab & line break characters actually. To display this nicely, you could do:

var withLineBreaks = json.Replace("\\n", "\n").Replace("\\t", "\t");

However if you do that, the text that you're writing will be invalid JSON, and you'll have to strip out tab and line breaks when you read it back if you want to deserialize it.

于 2013-09-23T05:11:08.897 回答