为什么JSON.NET会添加所有这些反斜杠

时间:2012-01-31 21:31:26

标签: json json.net

请参阅:

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吗?我做错了什么?

谢谢!

2 个答案:

答案 0 :(得分:7)

您将多个独立的json字符串嵌入到彼此中。外部json编写者不知道你在里面构建了另一个json字符串,所以他们只是把它看作一个明文字符串,而不是json,并且必须转义引号。

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

答案 1 :(得分:1)

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