• 格式化JSON字符串


    提出需求

    异步调用获取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;
        }
  • 相关阅读:
    NHbiernate 配置
    NHibernate开发入门
    Thread 线程简单例子
    C#中委托和事件
    DataGridView 去掉多余的列
    ASP.NET C# 有程序集加不了解决办法
    oracle“记录被另一个用户锁住”
    Android 控件属性
    Android 入门
    MVC 视频笔记
  • 原文地址:https://www.cnblogs.com/shya/p/4416116.html
Copyright © 2020-2023  润新知