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不反斜線?我在做什麼錯?
謝謝!
因此,您是說整個JsonWriter基礎結構不適用於JSON對象而不是平面JSON對象? – Barka 2012-01-31 22:01:46
不,但一次完成mycollections.add,建立你的數據結構,然後把所有東西傳遞給json作者。 – 2012-01-31 22:37:13