C#后台格式化JSON字符串显示

时间:2020-12-25 04:59:18

很多时候我们从服务器上获取的JSON字符串是没有格式化的,如下:

{"BusinessId":null,"Code":200,"Data":{"linkResult":false,"linkURL":null},"Message":"未找到相关父字典集","Result":false}

而我们往往是想以以下的格式化方式显示,也容易看懂。如下:

{
"BusinessId": null,
"Code": 200,
"Data": {
"linkResult": false,
"linkURL": null
},
"Message": "未找到相关父字典集",
"Result": false
}

我们可以通过以下方法:

引入命名空间

1、using System.IO;

2、using Newtonsoft.Json;

private string ConvertJsonString(string str)
{
try
{
//格式化json字符串
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();
} return str;
}
catch (Exception ex)
{ }
}

C#后台格式化JSON字符串显示