这几天都在和JSON做斗争,又不想加入第三方lib,于是出现了如下产物:
需引用命名空间
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public static string DictionaryToJson(Dictionary<string, object> dictionary)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
String Tjson = jss.Serialize(dictionary);
Tjson = Tjson.Replace("[{", "[\r{").Replace("}]", "}\r]").Replace("{\"", "{\r\"").Replace("}", "\r}");
Tjson = Tjson.Replace("\",", "\",\r").Replace("},", "},\r").Replace("],", "],\r");
String linesign = "";
for (int n = 0; n < Tjson.Length; n++)
{
if (Tjson[n] == '\r' && Tjson[n - 1] == '{') linesign = linesign + " ";
else if (Tjson[n] == '\r' && Tjson[n - 1] == '[') linesign = linesign + " ";
else if (Tjson[n] == '\r' && Tjson[n + 1] == ']') linesign = linesign.Remove(0, 4);
else if (Tjson[n] == '\r' && Tjson[n + 1] == '}') linesign = linesign.Remove(0, 4);
if (Tjson[n] == '\r')
{
Tjson = Tjson.Insert(n + 1, "\n" + linesign);
n = n + linesign.Length + 1;
}
}
return Tjson;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
目前自用,暂未发现什么问题,只是效率有点低下。若有问题,欢迎指出
------解决思路----------------------
楼主不过是对 JavaScriptSerializer.Serialize 方法的结果(一个紧凑的格式)进行展开而已
至于遭到那么多的非议吗?