【问题标题】:Why is JSON.NET adding all these backslashes为什么 JSON.NET 添加所有这些反斜杠
【发布时间】:2012-01-31 21:31:26
【问题描述】:

请看:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.IO;
namespace TestJson2
{
    class Program
    {
        private static List<string> myCollections;

        static void Main(string[] args)
        {
            myCollections = new List<string>();

            myCollections.Add("frog");
            myCollections.Add("dog");
            myCollections.Add("cat");

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            using (JsonWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = Formatting.None;

                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName("id");
                jsonWriter.WriteValue("12345");

                jsonWriter.WritePropertyName("title");
                jsonWriter.WriteValue("foo");

                string animals = CollectionToJson();
                jsonWriter.WritePropertyName("animals");
                jsonWriter.WriteValue(animals);

                jsonWriter.WriteEndObject();
            }
            var result = sw.ToString();
        }
        private static string CollectionToJson()
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            using (JsonWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = Formatting.None;

                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName("animals");
                jsonWriter.WriteStartArray();
                foreach (var animal in myCollections)
                {
                    jsonWriter.WriteValue(animal);
                }
                jsonWriter.WriteEndArray();
                jsonWriter.WriteEndObject();
            }
            return sw.ToString();
        }
    }


}

结果变量的内容最终是:

{"id":"12345","title":"foo","animals":"{\"animals\":[\"frog\",\"dog\",\"cat\"]}"}

现在,随着 json 层次结构变得更深(为了简洁起见,我没有在这里显示多个层),斜线变成了多个:\\\。我知道我们需要转义 " 所以它不会终止字符串,但是这个字符串的最终用户不应该只看到没有反斜杠的 JSON 吗?我做错了什么?

谢谢!

【问题讨论】:

    标签: json json.net


    【解决方案1】:

    您正在相互嵌入多个独立的 json 字符串。外部 json 编写者不知道您在内部构建了另一个 json 字符串,因此他们只是将其视为纯文本字符串,而不是 json,并且必须转义引号。

    不是在 json on json on ....上构建 json,而是构建一个数据结构并将其传递给单个 JSON 构建器。

    【讨论】:

    • 所以你是说整个 JsonWriter 基础设施不适用于 JSON 对象而不是平面 JSON 对象?
    • 没有。但是一次性完成你的 mycollections.add 东西,建立你的数据结构,然后将整个东西传递给 json writer。
    【解决方案2】:

    创建一个 C# 对象来表示您的数据并使用 JsonSerializer 将其转换为 json 字符串会简单得多。

    【讨论】:

      猜你喜欢
      • 2012-05-06
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 2016-03-12
      • 2015-10-23
      • 2021-11-16
      相关资源
      最近更新 更多