推荐使用方法二!
方法一:
首先导入动态库 Newtonsoft.Json.dll
调用这个方法,传入json字符串,会返回格式化后的json字符串
/// <summary>
/// 格式化json
/// </summary>
/// <param name="str">输入json字符串</param>
/// <returns>返回格式化后的字符串</returns>
public static string ConvertJsonString(string str)
{
JsonSerializer serializer = new JsonSerializer();
TextReader tr = new StringReader(str);
JsonTextReader jtr = new JsonTextReader(tr);
object obj = serializer.Deserialize(jtr);
if (obj != null)
{
StringWriter textWriter = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
{
Formatting = Formatting.Indented,
Indentation = 4,
IndentChar = ' '
};
serializer.Serialize(jsonWriter, obj);
return textWriter.ToString();
}
else
{
return str;
}
}
方法二:
不需要动态库的(推荐)
/// <summary>
/// 格式转换:将Json缩进整理,用于查看
/// </summary>
/// <param name="sourceJson">源Json字符串</param>
/// <returns>整理后的Json字符串</returns>
public static string Json_StringFormat(string sourceJson)
{
sourceJson += " ";
int itap = 0;
string newjson = "";
for (int i = 0; i < sourceJson.Length - 1; i++)
{
if (sourceJson[i] == '{' || sourceJson[i] == '[')
{
itap++;
newjson += sourceJson[i] + "\n";
for (int a = 0; a < itap; a++) { newjson += "\t"; }
}
else if ((sourceJson[i] == '}' || sourceJson[i] == ']'))
{
itap--;
newjson += "\n";
for (int a = 0; a < itap; a++) { newjson += "\t"; }
newjson += sourceJson[i] + "" + ((sourceJson[i + 1] == ',') ? "," : "") + "\n";
if (sourceJson[i + 1] == ',') i++;
for (int a = 0; a < itap; a++) { newjson += "\t"; }
}
else if (sourceJson[i] != '}' && sourceJson[i] != ']' && sourceJson[i + 1] == ',')
{
newjson += sourceJson[i] + "" + sourceJson[i + 1] + "\n";
i++;
for (int a = 0; a < itap; a++) { newjson += "\t"; }
}
else
{
newjson += sourceJson[i];
}
}
return newjson;
}