转载: http://blog.csdn.net/ddgweb/article/details/39643747

一个简单示例:

String str = "{’name’:’cyf’,’id’:10,’items’:[{’itemid’:1001,’itemname’:’hello’},{’itemid’:1002,’itemname’:’hello2’}]}";             
//*** 读取JSON字符串中的数据 *******************************            
JsonData jd = JsonMapper.ToObject(str);          
String name = (String)jd["name"];  
long id = (long)jd["id"];            
JsonData jdItems = jd["items"];      
int itemCnt = jdItems.Count; 
// 数组 items 中项的数量 
foreach (JsonData item in jdItems)
// 遍历数组 items            
{int itemID = (int)item["itemid"];                
String itemName = (String)item["itemname"];        
}

//*** 将JsonData转换为JSON字符串 ***************************

String str2 = jd.ToJson();

LitJSON是一个.NET平台下处理JSON格式数据的类库,小巧、快速。它的源代码使用C#编写,可以通过任何.Net平台上的语言进行调用,目前最新版本为LitJSON 0.5.0。

与以下这几个.Net平台上的开源JSON库相比,LitJSON的性能遥遥领先:

Jayrock version 0.9.8316

LitJSON version 0.3.0

Newtonsoft Json.NET version 1.1

下面介绍LitJSON中常用的方法:

以下示例需要先添加引用LitJson.dll,再导入命名空间 using LitJson;

下载

1、Json 与 C#中 实体对象 的相互转换

例 1.1:使用 JsonMapper 类实现数据的转换

ublic class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime Birthday { get; set; }
    }
    public class JsonSample
    {
        public static void Main()
        {
            PersonToJson();
            JsonToPerson();
        }
        /// 
        /// 将实体类转换成Json格式
        /// 
        public static void PersonToJson()
        {
            Person bill = new Person();
            bill.Name = "www.87cool.com";
            bill.Age = 3;
            bill.Birthday = new DateTime(2007, 7, 17);
            string json_bill = JsonMapper.ToJson(bill);
            Console.WriteLine(json_bill);
            //输出:{"Name":"www.87cool.com","Age":3,"Birthday":"07/17/2007 00:00:00"}
        }

/// 
        /// 将Json数据转换成实体类
        /// 
        public static void JsonToPerson()
        {
            string json = @"
            {
                ""Name""    : ""www.87cool.com"",
                ""Age""      : 3,
                ""Birthday"" : ""07/17/2007 00:00:00""
            }";
            Person thomas = JsonMapper.ToObject(json);
            Console.WriteLine("’87cool’ age: {0}", thomas.Age);
            //输出:’87cool’ age: 3
        }
    }

例 1.2:使用 JsonMapper 类将Json字符串转换为C#认识的JsonData,再通过Json数据的属性名或索引获取其值。

在C#中读取JsonData对象 和 在JavaScript中读取Json对像的方法完全一样;

对Json的这种读取方式在C#中用起来非常爽,同时也很实用,因为现在很多网络应用提供的API所返回的数据都是Json格式的,

如Flickr相册API返回的就是json格式的数据。
        public static void LoadAlbumData(string json_text)
        {
            JsonData data = JsonMapper.ToObject(json_text);
            Console.WriteLine("Album’s name: {0}", data["album"]["name"]);
            string artist = (string)data["album"]["name"];
            int year = (int)data["album"]["year"];
            Console.WriteLine("First track: {0}", data["album"]["tracks"][0]);
        }

2、C# 中对 Json 的 Readers 和 Writers

例 2.1:JsonReader类的使用方法 
public class DataReader
{
    public static void Main ()
    {
        string sample = @"{
            ""name""  : ""Bill"",
            ""age""  : 32,
            ""awake"" : true,
            ""n""    : 1994.0226,
            ""note""  : [ ""life"", ""is"", ""but"", ""a"", ""dream"" ]
          }";
        ReadJson (sample);
    }
    //输出所有Json数据的类型和值
    public static void ReadJson (string json)
    {
        JsonReader reader = new JsonReader (json);
        
        Console.WriteLine ("{0,14} {1,10} {2,16}", "Token", "Value", "Type");
        Console.WriteLine (new String (’-’, 42));
        while (reader.Read())
        {
            string type = reader.Value != null ? reader.Value.GetType().ToString() : "";
            Console.WriteLine("{0,14} {1,10} {2,16}", reader.Token, reader.Value, type);
        }
    }
}
      
//输出结果:

//      Json类型        值          C#类型
//------------------------------------------
//  ObjectStart                            
//  PropertyName      name    System.String
//        String      Bill    System.String
//  PropertyName        age    System.String
//          Int        32    System.Int32
//  PropertyName      awake    System.String
//      Boolean      True  System.Boolean
//  PropertyName          n    System.String
//        Double  1994.0226    System.Double
//  PropertyName      note    System.String
//    ArrayStart                            
//        String      life    System.String
//        String        is    System.String
//        String        but    System.String
//        String          a    System.String
//        String      dream    System.String
//      ArrayEnd                            
//    ObjectEnd

例 2.2:JsonWriter类的使用方法 
public class DataReader
{
    //通过JsonWriter类创建一个Json对象
    public static void WriteJson ()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        JsonWriter writer = new JsonWriter (sb);
        writer.WriteArrayStart ();
        writer.Write (1);
        writer.Write (2);
        writer.Write (3);
        writer.WriteObjectStart ();
        writer.WritePropertyName ("color");
        writer.Write ("blue");
        writer.WriteObjectEnd ();
        writer.WriteArrayEnd ();
        Console.WriteLine (sb.ToString ());
        //输出:[1,2,3,{"color":"blue"}]
    }
}

.NET平台开源JSON序列化的更多相关文章

  1. [C#技术] .NET平台开源JSON库LitJSON的使用方法

    一个简单示例: String str = "{’name’:’cyf’,’id’:10,’items’:[{’itemid’:1001,’itemname’:’hello’},{’itemi ...

  2. .NET平台开源JSON库LitJSON的使用方法

    下载地址:LitJson.dll下载 一个简单示例: String str = "{'name':'cyf','id':10,'items':[{'itemid':1001,'itemnam ...

  3. (转).NET平台开源JSON库LitJSON的使用方法

    一个简单示例: String str = "{’name’:’cyf’,’id’:10,’items’:[{’itemid’:1001,’itemname’:’hello’},{’itemi ...

  4. 解决MVC Json序列化的循环引用问题/EF Json序列化循引用问题---Newtonsoft.Json

    1..Net开源Json序列化工具Newtonsoft.Json中提供了解决序列化的循环引用问题: 方式1:指定Json序列化配置为 ReferenceLoopHandling.Ignore 方式2: ...

  5. Swifter.Json 可能是 .Net 平台迄今为止性能最佳的 Json 序列化库【开源】

    Json 简介 Json (JavaScript Object Notation) 是一种轻量级的数据交换格式.它作为目前最欢迎的数据交换格式,也是各大开源贡献者的必争之地,如:阿里爸爸的 fastj ...

  6. Json序列化之.NET开源类库Newtonsoft.Json的研究

     一.Json简介 JSON(全称为JavaScript Object Notation) 是一种轻量级的数据交换格式.它是基于JavaScript语法标准的一个子集. JSON采用完全独立于语言的文 ...

  7. 迄今为止 .Net 平台功能最强大,性能最佳的 JSON 序列化和反序列化库。

    Swifter.Json 这是迄今为止 .Net 平台功能最强大,性能最佳的 JSON 序列化和反序列化库. Github : https://github.com/Dogwei/Swifter.Js ...

  8. [.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类

    [.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类 本节导读: 关于JSON序列化,不能 ...

  9. .NET平台开源项目速览(3)小巧轻量级NoSQL文件数据库LiteDB

    今天给大家介绍一个不错的小巧轻量级的NoSQL文件数据库LiteDB.本博客在2013年也介绍过2款.NET平台的开源数据库: 1.[原创]开源.NET下的XML数据库介绍及入门 2.[原创]C#开源 ...

随机推荐

  1. 1.Ventuz 介绍

    Ventoz能做什么? Ventuz是一款实时图文包装内容创作.制作和播出控制软件.Ventuz专注于高端视听内容的制作,包括交互展示和大型活动.视频墙.广播电视在线包装及演播室舞台及灯光控制等领域. ...

  2. 图的连通性问题的小结 (双连通、2-SAT)

    图的连通性问题包括: 1.强连通分量. 2.最小点基和最小权点基. 3.双连通. 4.全局最小割. 5.2-SAT 一.强连通分量 强连通分量很少单独出题,一般都是把求强连通分量作为缩点工具. 有三种 ...

  3. Redhat/CentOS xfs文件系统及磁盘挂载

    #!/bin/sh #DEVICE_LIST=""DEVICE_LIST="/dev/sda /dev/sdb /dev/sdc /dev/sdd /dev/sde /d ...

  4. C++序列化使用

    error C2248 无法访问私有成员 :原因 ifstream 作为参数必须传引用! (1):C++使用STL序列化:原文链接:http://blog.csdn.net/pandaxcl/arti ...

  5. 模拟试题B

    模拟试题B 一.单项选择题(2′*8 =16′) 1.灰度等级为256级,分辨率为2048*1024的显示器,至少需要的帧缓存容量为( ) A)512KB B)1MB C)2MB D)3MB 2.在多 ...

  6. 浅谈[^>]在正则中的2种用法

    /^A/会匹配"An e"中的A,但是不会匹配"ab A"中的A,此时^A的意思是“匹配开头的A” /[^a-z\s]/会匹配"my 3 sister ...

  7. JavaScript对原始数据类型的拆装箱操作

    JS中的基本类型: boolean null undefined string number symbol 每当读取一个基本类型的时候,会隐式的自动进行装箱操作(即:将一个基本类型变成对象): var ...

  8. 关于HTML表格中插入背景图片的问题_百度知道 3个回答 - 提问时间: 2009年03月23日 最佳答案: <tr style="background-image:url(1.jpg)"> (这事设置背景图片) <img src="images/bbs_student1.gif" />如果是这样的就是直接插入图片。你看看,...

    关于HTML表格中插入背景图片的问题_百度知道 3个回答 - 提问时间: 2009年03月23日 最佳答案: <tr style="background-image:url(1.jpg ...

  9. windows 查看端口号被占用

    1.netstat  -ano 2.tasklist | findstr xxx 3.进程管理杀掉

  10. github插件

    可能是迄今为止最好的GitHub代码浏览插件,基本实现浏览器变成代码阅读器,支持目录列表,交叉索引等功能: O网页链接 ​​​​ http://weibo.com/1963193953/Fdj2cFQ ...