码迷,mamicode.com
首页 > Web开发 > 详细

JsonFormatter PrettyPrint

时间:2015-07-15 09:17:11      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace prettycode.org
{
    public static class JsonFormatter
    {
        public static string JsCasePropertyNames(string json)
        {
            var buffer = new StringBuilder();
            var inString = false;

            for (var i = 0; i < json.Length; i++)
            {
                var currentChar = json[i];
                char? previousChar = (i > 0) ? (char?)json[i - 1] : null;

                if (currentChar == " && previousChar.HasValue && previousChar != \\)
                {
                    inString = !inString;
                }

                if (inString && currentChar == " && "{,".Contains(previousChar.Value))
                {
                    buffer.Append("\"" + Char.ToLowerInvariant(json[++i]));
                }
                else
                {
                    buffer.Append(currentChar);
                }
            }

            return buffer.ToString();
        }

        public static string PrettyPrint(string json, string indent = "   ")
        {
            var buffer = new StringBuilder();
            var depth = 0;
            var inString = false;

            for (var i = 0; i < json.Length; i++)
            {
                var currentChar = json[i];

                if (currentChar == " && i > 0 && json[i - 1] != \\)
                {
                    inString = !inString;
                }

                if (inString)
                {
                    buffer.Append(currentChar);
                }
                else if (currentChar == { || currentChar == [)
                {
                    buffer.Append(currentChar + "\n" + string.Concat(Enumerable.Repeat(indent, ++depth)));
                }
                else if (currentChar == } || currentChar == ])
                {
                    buffer.Append("\n" + string.Concat(Enumerable.Repeat(indent, --depth)) + currentChar);
                }
                else if (currentChar == ,)
                {
                    buffer.Append(",\n" + string.Concat(Enumerable.Repeat(indent, depth)));
                }
                else if (currentChar == :)
                {
                    buffer.Append(": ");
                }
                else
                {
                    buffer.Append(currentChar);
                }
            }

            return buffer.ToString();
        }
    }
}

 

JsonFormatter PrettyPrint

标签:

原文地址:http://www.cnblogs.com/lummon/p/4647266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!