请参阅:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果变量的内容最终为:
{"id":"12345","title":"foo","animals":"{\"animals\":[\"frog\",\"dog\",\"cat\"]}"}
Run Code Online (Sandbox Code Playgroud)
现在随着json层次结构变得越来越深(为了简洁我没有在这里展示多个层),斜线变得多了:\\\.我知道我们需要转义"所以它不会终止字符串,但是这个字符串的最终用户不应该只看到没有反斜杠的JSON吗?我做错了什么?
谢谢!
您将多个独立的json字符串嵌入到彼此中.外部json编写者不知道你在里面构建了另一个json字符串,所以他们只是把它看作一个明文字符串,而不是json,并且必须转义引号.
而不是在json on json on jon上构建json,构建一个数据结构并将其传递给单个JSON构建器.
| 归档时间: |
|
| 查看次数: |
3463 次 |
| 最近记录: |