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

摘要:
它的源代码是用C#编写的,可以被上的任何语言调用。网络平台。最新版本是LitJSON 0.5.0。LitJSON中的常用方法介绍如下:对于以下示例,需要添加引用LitJSON。dll,然后使用LitJson导入命名空间;可以转到http://litjson.sourceforge.net转到下载。

一个简单示例:

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。

下面介绍LitJSON中常用的方法: 
以下示例需要先添加引用LitJson.dll,再导入命名空间 using LitJson; 
可以到http://litjson.sourceforge.net去下载。

1、Json 与 C#中 实体对象 的相互转换 
例 1.1:使用 JsonMapper 类实现数据的转换 
public 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库LitJSON的使用方法》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇iterm2 常用操作MySQL 详细解读undo log :insert undo,update undo下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

原有vue项目接入typescript

原有vue项目接入typescript 为什么要接入typescript javascript由于自身的弱类型,使用起来非常灵活。 这也就为大型项目、多人协作开发埋下了很多隐患。如果是自己的私有业务倒无所谓,主要是对外接口和公共方法,对接起来非常头疼。主要表现在几方面: 参数类型没有校验,怎么传都有,有时会出现一些由于类型转换带来的未知问题。 接口文档不...

adb shell 查看系统属性(用来判断特殊的操作系统)

一般来讲,在android程序开发中进行需要判断设备类型和系统版本 1、设备类型判断(android.os.Build.MODEL) 比如判断属于Google Nexus 5,Nexus 7,MIUI v5, MIUI v6,三星设备,魅族设备等; 这类型的问题都使用的android.os.Build.MODEL来判断,android.os.Build.M...

[SpringBoot] SpringApplication.run 执行流程

作者:王奕然链接:https://www.zhihu.com/question/21346206/answer/101789659来源:知乎著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。建议不要硬着头皮看spring代码,本身的代码800多m,就是不上班开始看也不知道什么时候看完。如果想学学ioc,控制反转这些建议看看jodd项目,...

java加解密(一)

1、杂谈   1、古典密码学     核心:替换法/位移法(凯撒加密)     破解方法:频率分析法,即研究字母和字母组合在文本中出现的概率。   2、近代密码学:     恩尼格玛机     被图灵破解   3、现代密码学:     1、散列函数:散列函数,也叫杂凑函数、摘要函数或哈希函数,可将任意长度的消息经过运算,变成固定长度数值,常...

从未如此简单:10分钟带你逆袭Kafka!【转】

【51CTO.com原创稿件】Apache Kafka 是一个快速、可扩展的、高吞吐的、可容错的分布式“发布-订阅”消息系统, 使用 Scala 与 Java 语言编写,能够将消息从一个端点传递到另一个端点。 较之传统的消息中间件(例如 ActiveMQ、RabbitMQ),Kafka 具有高吞吐量、内置分区、支持消息副本和高容错的特性,非常适合大规模消息...

springboot 使用webflux响应式开发教程(二)

本篇是对springboot 使用webflux响应式开发教程(一)的进一步学习。 分三个部分: 数据库操作webservicewebsocket 创建项目,artifactId = trading-service,groupId=io.spring.workshop。选择Reactive Web , Devtools, Thymeleaf , React...