gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:43:14 25 4
gpt4 key购买 nike

请看:

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 编写者不知道你在里面构建了另一个 json 字符串,所以他们只是将其视为明文字符串,而不是 json,并且必须对引号进行转义。

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

关于json - 为什么 JSON.NET 添加所有这些反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9087253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com