首页 > Web开发 > 详细

格式化JSON字符串

时间:2015-04-11 06:32:33      阅读:248      评论:0      收藏:0      [点我收藏+]

提出需求

异步调用获取JSON数据时非常不直观,每次都需要格式化一次,才能直观的看到数据集合的结构,现在需要实现输出带缩进的格式。

实现效果

在浏览器的查看源文件中已经实现格式化,如果是页面使用,可以直接赋值给textarea同样能以格式化后的效果显示。

技术分享

实现代码

public static String Format(string text)
    {
        string result = string.Empty;
        try
        {
        
            JsonSerializer serializer = new JsonSerializer();
            JsonReader reader = new JsonTextReader(new StringReader(text));
            object obj2 = serializer.Deserialize(reader);
            if (obj2 != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 4,
                    IndentChar =    
                };
                serializer.Serialize(jsonWriter, obj2);
                result = textWriter.ToString();
            }
        }
        catch (Exception exception)
        {
            LogHelper.Write(exception.Message);
            result = exception.Message;
        }
        return result;
    }

 

格式化JSON字符串

原文:http://www.cnblogs.com/shya/p/4416116.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!