C#格式化json字符串的方法分析

本文实例讲述了C#格式化json字符串的方法。分享给大家供大家参考,具体如下:

将Json字符串转化成格式化表示的方法: 字符串反序列化为对象-->对象再序列化为字符串

使用Newtonsoft.Json提供的API,下载地址:http://www.newtonsoft.com/json

很多时候我们需要将json字符串以

{
  "status": 1,
  "sum": 9
}

这种方式显示,而从服务端取回来的时候往往是这样

{"status": 1, "sum": 9}

什么?无所谓?

如果数据很庞大的时候,比如这样

代码如下:

{"status":1,"totalcount":2,"list":[{"id":"2305b1e2-4e31-4fd3-8eb6-db57641914df","code":"8147056167227050270","title":"testing","type":"产品","status":"已处理","datetime":"2014-07-12T21:16:46","replycontent":"好的,只是测试"},{"id":"3a6546f6-49a7-4a17-b679-b3812b12b27e","code":"8147056167227050269","title":"我建议龙头有多种选配方式","type":"产品","status":"未处理","datetime":"2014-07-12T18:49:08.933","replycontent":""},{"id":"f735e461-ca72-4b44-8d7b-cd97ac09802f","code":"8147056167227050268","title":"这个产品不怎么好,不好用","type":"产品","status":"未处理","datetime":"2014-07-12T15:06:19.1","replycontent":""},{"id":"15926d9d-f469-4921-b01d-4b48ef8bd93d","code":"7141054273018032465","title":"jdjbcn","type":"服务","status":"未处理","datetime":"2014-05-27T01:03:46.477","replycontent":""},{"id":"1debf78f-42b3-4037-b71f-34075eed92bc","code":"4141051277003536211","title":"jdjbxn.x","type":"服务","status":"未处理","datetime":"2014-05-27T00:53:21.18","replycontent":""},{"id":"27593c52-b327-4557-8106-b9156df53909","code":"1143051276001357050","title":"ghggghh","type":"服务","status":"未处理","datetime":"2014-05-27T00:35:05.933","replycontent":""},{"id":"040198fc-b466-46c1-89d8-0514fbde9480","code":"4142053251166372433","title":"你好,你知道啦,我不喜欢白色浴缸","type":"服务","status":"未处理","datetime":"2014-05-25T16:37:43.853","replycontent":""},{"id":"16185418-d461-4e98-83c3-824eb7e344d6","code":"4145058213013197148","title":"hdjbchh","type":"服务","status":"未处理","datetime":"2014-05-21T01:19:14.903","replycontent":""},{"id":"6c043404-c1db-42e8-adeb-d4880fa7d1b5","code":"0142051185128085372","title":"ghhjdhd","type":"服务","status":"未处理","datetime":"2014-05-18T12:08:37.997","replycontent":""},{"id":"2dca1a38-a32b-4955-a99c-2ed7d6de60fa","code":"3146050186122030382","title":"hsibcn","type":"服务","status":"未处理","datetime":"2014-05-18T12:03:38.913","replycontent":""}]}

如果没有格式化,将很难查看。。。

使用下面的方法,将结果格式化为这样

{
  "status": 1,
  "totalcount": 2,
  "list": [
    {
      "id": "2305b1e2-4e31-4fd3-8eb6-db57641914df",
      "code": "8147056167227050270",
      "title": "testing",
      "type": "产品",
      "status": "已处理",
      "datetime": "2014-07-12T21:16:46",
      "replycontent": "好的,只是测试"
    },
    {
      "id": "3a6546f6-49a7-4a17-b679-b3812b12b27e",
      "code": "8147056167227050269",
      "title": "我建议龙头有多种选配方式",
      "type": "产品",
      "status": "未处理",
      "datetime": "2014-07-12T18:49:08.933",
      "replycontent": ""
    },
    {
      "id": "f735e461-ca72-4b44-8d7b-cd97ac09802f",
      "code": "8147056167227050268",
      "title": "这个产品不怎么好,不好用",
      "type": "产品",
      "status": "未处理",
      "datetime": "2014-07-12T15:06:19.1",
      "replycontent": ""
    },
    {
      "id": "15926d9d-f469-4921-b01d-4b48ef8bd93d",
      "code": "7141054273018032465",
      "title": "jdjbcn",
      "type": "服务",
      "status": "未处理",
      "datetime": "2014-05-27T01:03:46.477",
      "replycontent": ""
    },
    {
      "id": "1debf78f-42b3-4037-b71f-34075eed92bc",
      "code": "4141051277003536211",
      "title": "jdjbxn.x",
      "type": "服务",
      "status": "未处理",
      "datetime": "2014-05-27T00:53:21.18",
      "replycontent": ""
    },
    {
      "id": "27593c52-b327-4557-8106-b9156df53909",
      "code": "1143051276001357050",
      "title": "ghggghh",
      "type": "服务",
      "status": "未处理",
      "datetime": "2014-05-27T00:35:05.933",
      "replycontent": ""
    },
    {
      "id": "040198fc-b466-46c1-89d8-0514fbde9480",
      "code": "4142053251166372433",
      "title": "你好,你知道啦,我不喜欢白色浴缸",
      "type": "服务",
      "status": "未处理",
      "datetime": "2014-05-25T16:37:43.853",
      "replycontent": ""
    },
    {
      "id": "16185418-d461-4e98-83c3-824eb7e344d6",
      "code": "4145058213013197148",
      "title": "hdjbchh",
      "type": "服务",
      "status": "未处理",
      "datetime": "2014-05-21T01:19:14.903",
      "replycontent": ""
    },
    {
      "id": "6c043404-c1db-42e8-adeb-d4880fa7d1b5",
      "code": "0142051185128085372",
      "title": "ghhjdhd",
      "type": "服务",
      "status": "未处理",
      "datetime": "2014-05-18T12:08:37.997",
      "replycontent": ""
    },
    {
      "id": "2dca1a38-a32b-4955-a99c-2ed7d6de60fa",
      "code": "3146050186122030382",
      "title": "hsibcn",
      "type": "服务",
      "status": "未处理",
      "datetime": "2014-05-18T12:03:38.913",
      "replycontent": ""
    }
  ]
}

实现代码如下:

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;
  }
}

PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json

JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat

在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans

更多关于C#相关内容还可查看本站专题:《C#字符串操作技巧总结》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#程序设计之线程使用技巧总结》、《C#中XML文件操作技巧汇总》、《C#数据结构与算法教程》、《C#数组操作技巧总结》及《C#面向对象程序设计入门教程》

希望本文所述对大家C#程序设计有所帮助。

(0)

相关推荐

  • C#中图片、二进制与字符串的相互转换方法

    本文实例讲述了C#中图片.二进制与字符串的相互转换方法.分享给大家供大家参考,具体如下: protected void Button1_Click(object sender, EventArgs e) { //图片转二进制 byte[] imageByte = GetPictureData(Server.MapPath("./uploadfile/111.png")); //二进制转换成字符串 string picStr = Convert.ToBase64String(imageB

  • C# 字符串string和内存流MemoryStream及比特数组byte[]之间相互转换

    定义string变量为str,内存流变量为ms,比特数组为bt 1.字符串转比特数组 复制代码 代码如下: (1)byte[] bt=System.Text.Encoding.Default.GetBytes("字符串"); (2)byte[] bt=Convert.FromBase64String("字符串"); 2.字符串转流 复制代码 代码如下: (1)MemoryStream ms=new MemoryStream(System.Text.Encoding.

  • C#基于正则表达式删除字符串中数字或非数字的方法

    本文实例讲述了C#基于正则表达式删除字符串中数字或非数字的方法.分享给大家供大家参考,具体如下: /// 去掉字符串中的数字 public static string RemoveNumber(string key) { return Regex.Replace(key, @"\d", ""); } //去掉字符串中的非数字 public static string RemoveNotNumber(string key) { return Regex.Replace

  • 在C#及.NET框架中使用StringBuilder类操作字符串的技巧

    但如果性能的优劣很重要,则应该总是使用 StringBuilder 类来串联字符串.下面的代码使用 StringBuilder 类的 Append 方法来串联字符串,因此不会有 + 运算符的链接作用产生. class StringBuilderTest { static void Main() { string text = null; // Use StringBuilder for concatenation in tight loops. System.Text.StringBuilder

  • C# string格式的日期时间字符串转为DateTime类型的方法

    方法一:Convert.ToDateTime(string) string格式有要求,必须是yyyy-MM-dd hh:mm:ss 方法二:Convert.ToDateTime(string, IFormatProvider) DateTime dt; DateTimeFormatInfo dtFormat = new System.GlobalizationDateTimeFormatInfo(); dtFormat.ShortDatePattern = "yyyy/MM/dd";

  • C#实现char字符数组与字符串相互转换的方法

    本文实例讲述了C#实现char字符数组与字符串相互转换的方法.分享给大家供大家参考,具体如下: 一.字符串转换为字符数组 char[] tempChar = sourceString.ToCharArray(); 二.字符数组转换为字符串 //方法一 string str = string.Join("", tempChar); //方法二 string str = string.Concat<char>(tempChar); //方法三 string str = new

  • C#正则表达式匹配与替换字符串功能示例

    本文实例讲述了C#正则表达式匹配与替换字符串功能.分享给大家供大家参考,具体如下: 事例一:\w+=>[A-Za-z1-9_],\s+=>任何空白字符,()=>捕获 string text = @"public string testMatchObj string s string match "; string pat = @"(\w+)\s+(string)"; // Compile the regular expression. Regex

  • C#后台接受前台JSON字符串装换成字典集合处理

    一直以来,我们都是在服务端查询出结果生成JSON字符串,供前端调用,那么我们能否把从前端接受的JSON字符串转换成字典集合,让后台处理呢? 比如从前端接收:{'size':'10', 'weight':'10kg'} 在服务端转换成:[{size:"10"},{weight:"10kg"}]这样的字典集合 通过Newtonsoft的DeserializeObject<Dictionary<string, string>>方法可以把JSON字符

  • C# DataTable中Compute方法用法集锦(数值/字符串/运算符/表等操作)

    本文实例讲述了C# DataTable中Compute方法用法.分享给大家供大家参考,具体如下: Compute函数的参数就两个:Expression,和Filter. Expresstion是计算表达式,关于Expression的详细内容请看这里: http://msdn2.microsoft.com/zh-cn/library/system.data.datacolumn.expression(VS.80).aspx 而Filter则是条件过滤器,类似sql的Where条件. DataTab

  • C#操作字符串方法总结实例代码

    废话不多说了,具体代码如下所述: staticvoid Main(string[] args) { string s =""; //(1)字符访问(下标访问s[i]) s ="ABCD"; Console.WriteLine(s[0]); // 输出"A"; Console.WriteLine(s.Length); // 输出4 Console.WriteLine(); //(2)打散为字符数组(ToCharArray) s ="ABC

随机推荐