为什么JSON.NET会添加所有这些反斜杠
请参阅:为什么JSON.NET会添加所有这些反斜杠,json,json.net,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&g
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();
}
}
}
现在,随着json层次结构越来越深(为了简洁起见,这里不显示多个层),斜杠变得越来越多:\\\
。我理解我们需要转义“所以它不会终止字符串,但是这个字符串的最终用户不应该看到没有反斜杠的JSON吗?我做错了什么
谢谢!您在彼此内部嵌入了多个独立的json字符串。外部json编写者不知道您在内部构建了另一个json字符串,因此他们只将其视为纯文本字符串,而不是json,并且必须转义引号
不要在json上的json上构建json,而是构建一个数据结构并将其传递给单个json生成器。只需创建一个C#对象来表示您的数据,然后使用
JsonSerializer
将其转换为json字符串,这会简单得多。您是说整个JsonWriter基础结构不适用于除了平面JSON对象之外的JSON对象?不。但是请执行mycollections。一次添加所有内容,构建数据结构,然后将整个内容传递给JSON编写器。
{"id":"12345","title":"foo","animals":"{\"animals\":[\"frog\",\"dog\",\"cat\"]}"}