C# winform格式化Json

//格式化Json
private string ConvertStringToJson(string str)

{
//格式化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();
}
else
{
return str;
}
}
private void button16_Click(object sender, EventArgs e)
{
string str = textBox2.Text;
textBox2.Text = ConvertStringToJson(str);

}

posted @ 2020-05-11 14:46  天空之上、只有蓝黑  阅读(1482)  评论(0编辑  收藏  举报