json作为常用数据文件,为了传输的效率,在传输前要进行压缩,而在传输后要进行格式化,以便阅读。下面是使用C#完成的格式化和压缩代码。

 public static string Compress(string json)
{
StringBuilder sb = new StringBuilder();
using (StringReader reader = new StringReader(json))
{
int ch = -;
int lastch = -;
bool isQuoteStart = false;
while ((ch = reader.Read()) > -)
{
if ((char)lastch != '\\' && (char)ch == '\"')
{
if (!isQuoteStart)
{
isQuoteStart = true;
}
else
{
isQuoteStart = false;
}
}
if (!Char.IsWhiteSpace((char)ch) || isQuoteStart)
{
sb.Append((char)ch);
}
lastch = ch;
}
}
return sb.ToString();
}

因为在json中"是用作隔离key和value的,而"又可以作为value中的一部分,所以在处理中要判断是否是单独的",还是作为隔离符号,所以要进行如上的判断。

public static string Format(string json)
{
string strCompress = Compress(json);
StringBuilder sb = new StringBuilder();
#region format using (StringReader reader = new StringReader(strCompress))
{
using (StringWriter writer = new StringWriter(sb))
{
int ch = -;
int lastch = -;
bool isQuoteStart = false;
while ((ch = reader.Read()) > -)
{
StringBuilder temp = new StringBuilder();
switch ((char)ch)
{
case '{':
if (isQuoteStart)
{
temp.Append('{');
}
else
{
temp.Append('{');
if ((char)reader.Peek() != '}')
{
temp.Append(Environment.NewLine);
}
}
break;
case '}':
if (isQuoteStart)
{
temp.Append('}');
}
else
{
if ((char)lastch != '{' && (char)lastch != '}')
{
temp.Append(Environment.NewLine);
}
temp.Append('}');
if ((char)reader.Peek() != ',')
{
temp.Append(Environment.NewLine);
}
}
break;
case '[':
if (isQuoteStart)
{
temp.Append('[');
}
else
{
temp.Append('[');
if ((char)reader.Peek() != ']')
{
temp.Append(Environment.NewLine);
}
}
break;
case ']':
if (isQuoteStart)
{
temp.Append(']');
}
else
{
if ((char)lastch != '[' && (char)lastch != ']')
{
temp.Append(Environment.NewLine);
}
temp.Append(']');
if ((char)reader.Peek() != ',' && (char)reader.Peek() != '}')
{
temp.Append(Environment.NewLine);
}
}
break;
case '\"':
if ((char)lastch != '\\')
{
if (!isQuoteStart)
{
isQuoteStart = true;
}
else
{
isQuoteStart = false;
}
}
temp.Append("\"");
break;
case ':':
if (isQuoteStart)
{
temp.Append(':');
}
else
{
temp.Append(':');
temp.Append(" ");
}
break;
case ',':
if (isQuoteStart)
{
temp.Append(',');
}
else
{
temp.Append(',');
temp.Append(Environment.NewLine);
}
break;
case ' ':
if (isQuoteStart)
{
temp.Append(" ");
}
else
{
temp.Append("");
temp.Append(Environment.NewLine);
}
break;
default:
temp.Append((char)ch);
break;
}
writer.Write(temp.ToString());
lastch = ch;
}
}
}
#endregion format #region indent
StringBuilder res = new StringBuilder();
using (StringReader reader = new StringReader(sb.ToString()))
{
using (StringWriter writer = new StringWriter(res))
{
string str = null; int nspace = ;
string space = "\t";
bool bEndMid = false;
while ((str = reader.ReadLine()) != null)
{
if (str.Length == ) continue;
if (str.EndsWith("},"))
{
nspace--;
}
StringBuilder temp = new StringBuilder();
if (!bEndMid)
{
for (int i = ; i < (str.EndsWith("],") || (str.EndsWith("}") && !str.EndsWith("{}")) || str.EndsWith("]") ? nspace - : nspace); i++)
{
temp.Append(space);
}
} temp.Append(str);
if (str.EndsWith("["))
{
writer.Write(temp);
bEndMid = true;
}
else
{
writer.WriteLine(temp);
bEndMid = false;
}
if (!(str.EndsWith("{}") || str.EndsWith("[]")))
{
if (str.StartsWith("{") || str.EndsWith("{") ||
str.EndsWith("["))
{
nspace++;
}
if (str.EndsWith("}") || str.EndsWith("]"))
{
nspace--;
}
}
}
}
}
return res.ToString();
#endregion indent
}

对"的考虑同compress,但格式化的话需要考虑到缩进,而放到一起考虑比较麻烦,所以先进行了格式化,然后在处理缩进,这样就简化了逻辑。

C#实现json压缩和格式化的更多相关文章

  1. SQL 横转竖 、竖专横 (转载) 使用Dapper.Contrib 开发.net core程序,兼容多种数据库 C# 读取PDF多级书签 Json.net日期格式化设置 ASPNET 下载共享文件 ASPNET 文件批量下载 递归,循环,尾递归 利用IDisposable接口构建包含非托管资源对象 《.NET 进阶指南》读书笔记2------定义不可改变类型

    SQL 横转竖 .竖专横 (转载)   普通行列转换 问题:假设有张学生成绩表(tb)如下: 姓名 课程 分数 张三 语文 74 张三 数学 83 张三 物理 93 李四 语文 74 李四 数学 84 ...

  2. PHP json字符串,格式化缩进显示

    PHP json字符串,格式化显示 /** * 格式化 */ class JsonFormatHelper { /** * json字符串缩进显示 * @param unknown $json * @ ...

  3. 对Json字符串进行格式化显示

    很多时候,我们拿Json字符串作为返回结果,但是当数据量多的时候,一堆的Json字符串看起来很不直观,这时候我们可以使用以下办法将Json字符串格式化一下再输出 var JsonUti = { //定 ...

  4. net.sf.json日期类型格式化输出

    net.sf.json 日期类型格式化输出 Date, Timestamp ; 编写工具类 package cn.jorcen.commons.util; import java.text.DateF ...

  5. 利用Gson将JSON数据进行格式化(pretty print)

    我们可以利用Gson包将String类型的JSON数据进行格式化. Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonPa ...

  6. 模拟实现JSON.stringiry 的格式化输出

    前言 这是一道笔试题,要求模拟实现JSON.stringiry 的格式化输出,按照层级缩进,输出易读格式,即完成以下方法 JSON.stringify(jsObj, null, 4); // 缩进4个 ...

  7. JSON字符串控制台格式化输出 java

    1.正常情况下返回的json数据格式如下: {"header":{"transSn":"e33128bb7622462ebfb2cbfcc46baa1 ...

  8. grunt配置太复杂?使用Qbuild进行文件合并、压缩、格式化等处理

    上次简单介绍了下Qbuild的特点和配置,其实实现一个自动化工具并不复杂,往简单里说,无非就是筛选文件和处理文件.但Qbuild的源码也并不少,还是做了不少工作的. 1. 引入了插件机制.在Qbuil ...

  9. Json.net日期格式化

    1. 全局设置,可以在App_Global中配置 JsonSerializerSettings setting = new JsonSerializerSettings(); JsonConvert. ...

随机推荐

  1. matlab中如何用rand产生相同的随机数

    直接给链接:rand()产生相同随机数

  2. KeyguardSliceView.java

    /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Versi ...

  3. padding填充属性

    内边距属性: 设置元素的内容与边框之间的距离. 分4个方向(上右下左): padding-top padding-right padding-bottom padding-left 说明:值不能为负值 ...

  4. linux三剑客之grep

    linux基础三剑客之grep 1.grep命令 基本介绍 grep命令是文本本过滤工具,是基于一个模式匹配文件的每一行,grep分类:egrep个fgrep. grep英文名:Global  sea ...

  5. rem 自适应适配方法

    rem是指相对于根元素(html)的字体大小的单位,它是一个相对单位,它是css3新增加的一个单位属性,我们现在有很多人用的都是px,但px是一个绝对单位,遇到分辨率不同的设备,做出的页面可能会乱,这 ...

  6. Centos中安装gitlab

    安装依赖: sudo yum install curl openssh-server openssh-clients postfix cronie sudo service postfix start ...

  7. socket端口绑定后通过bat干掉

    @echo off::port为需要去绑定端口set port=8888for /f "tokens=5 delims= " %%a in ('netstat -ano ^|fin ...

  8. flume安装配置

    1 下载安装包并解压 下载地址:http://flume.apache.org/download.html 解压:tar zxvf apache-flume-1.8.0-bin.tar.gz 2 配置 ...

  9. JavaScript线程(第八天)

    js是单线程的: js中的线程分为三种 1.页面渲染 2.主代码逻辑 3.事件触发: 下面我们来看一段代码 <script> setTimeout(function(){    conso ...

  10. 491. Increasing Subsequences

    这种increasing xxx 题真是老客户了.. 本题麻烦点在于不能重复, 但是和之前的那些 x sum的题目区别在于不能排序的 所以.... 我还是没搞定. 看了一个Java的思路是直接用set ...