首页 > 其他分享 >如何格式化json字符串

如何格式化json字符串

时间:2022-10-12 18:35:37浏览次数:53  
标签:格式化 textWriter json obj str 字符串 new

提问

C# 如何格式化json字符串

回答

private string ConvertJsonString(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;
            }
        }

标签:格式化,textWriter,json,obj,str,字符串,new
From: https://www.cnblogs.com/wuhailong/p/16785539.html

相关文章