地址:http://lbv.github.io/litjson/docs/quickstart.html

LitJSON Quickstart Guide

Introduction

JSON is a simple, yet powerful notation to specify data. It defines simple scalar types such as boolean, number (integers and reals) and string, and a couple of data structures: arrays (lists) and objects (dictionaries). For more information on the JSON format, visit JSON.org.

LitJSON is written in C#, and it’s intended to be small, fast and easy to use. It was developed on a GNU/Linux environment, using the Mono framework.

Quick Start

Mapping JSON to objects and vice versa

In order to consume data in JSON format inside .Net programs, the natural approach that comes to mind is to use JSON text to populate a new instance of a particular class; either a custom one, built to match the structure of the input JSON text, or a more general one which acts as a dictionary.

Conversely, in order to build new JSON strings from data stored in objects, a simple export–like operation sounds like a good idea.

For this purpose, LitJSON includes the JsonMapper class, which provides two main methods used to do JSON–to–object and object–to–JSON conversions. These methods are JsonMapper.ToObject and JsonMapper.ToJson.

Simple JsonMapper examples

As the following example demonstrates, the ToObject method has a generic variant, JsonMapper.ToObject<T>, that is used to specify the type of the object to be returned.

  1. using LitJson;
  2. using System;
  3. public class Person
  4. {
  5. // C# 3.0 auto-implemented properties
  6. public string Name { get; set; }
  7. public int Age { get; set; }
  8. public DateTime Birthday { get; set; }
  9. }
  10. public class JsonSample
  11. {
  12. public static void Main()
  13. {
  14. PersonToJson();
  15. JsonToPerson();
  16. }
  17. public static void PersonToJson()
  18. {
  19. Person bill = new Person();
  20. bill.Name = "William Shakespeare";
  21. bill.Age = 51;
  22. bill.Birthday = new DateTime(1564, 4, 26);
  23. string json_bill = JsonMapper.ToJson(bill);
  24. Console.WriteLine(json_bill);
  25. }
  26. public static void JsonToPerson()
  27. {
  28. string json = @"
  29. {
  30. ""Name"" : ""Thomas More"",
  31. ""Age"" : 57,
  32. ""Birthday"" : ""02/07/1478 00:00:00""
  33. }";
  34. Person thomas = JsonMapper.ToObject<Person>(json);
  35. Console.WriteLine("Thomas' age: {0}", thomas.Age);
  36. }
  37. }

Output from the example:

  1. {"Name":"William Shakespeare","Age":51,"Birthday":"04/26/1564 00:00:00"}
  2. Thomas' age: 57

Using the non–generic variant of JsonMapper.ToObject

When JSON data is to be read and a custom class that matches a particular data structure is not available or desired, users can use the non–generic variant of ToObject, which returns a JsonData instance. JsonData is a general purpose type that can hold any of the data types supported by JSON, including lists and dictionaries.

  1. using LitJson;
  2. using System;
  3. public class JsonSample
  4. {
  5. public static void Main()
  6. {
  7. string json = @"
  8. {
  9. ""album"" : {
  10. ""name"" : ""The Dark Side of the Moon"",
  11. ""artist"" : ""Pink Floyd"",
  12. ""year"" : 1973,
  13. ""tracks"" : [
  14. ""Speak To Me"",
  15. ""Breathe"",
  16. ""On The Run""
  17. ]
  18. }
  19. }
  20. ";
  21. LoadAlbumData(json);
  22. }
  23. public static void LoadAlbumData(string json_text)
  24. {
  25. Console.WriteLine("Reading data from the following JSON string: {0}",
  26. json_text);
  27. JsonData data = JsonMapper.ToObject(json_text);
  28. // Dictionaries are accessed like a hash-table
  29. Console.WriteLine("Album's name: {0}", data["album"]["name"]);
  30. // Scalar elements stored in a JsonData instance can be cast to
  31. // their natural types
  32. string artist = (string) data["album"]["artist"];
  33. int year = (int) data["album"]["year"];
  34. Console.WriteLine("Recorded by {0} in {1}", artist, year);
  35. // Arrays are accessed like regular lists as well
  36. Console.WriteLine("First track: {0}", data["album"]["tracks"][0]);
  37. }
  38. }

Output from the example:

  1. Reading data from the following JSON string:
  2. {
  3. "album" : {
  4. "name" : "The Dark Side of the Moon",
  5. "artist" : "Pink Floyd",
  6. "year" : 1973,
  7. "tracks" : [
  8. "Speak To Me",
  9. "Breathe",
  10. "On The Run"
  11. ]
  12. }
  13. }
  14. Album's name: The Dark Side of the Moon
  15. Recorded by Pink Floyd in 1973
  16. First track: Speak To Me

Readers and Writers

An alternative interface to handling JSON data that might be familiar to some developers is through classes that make it possible to read and write data in a stream–like fashion. These classes are JsonReader and JsonWriter.

These two types are in fact the foundation of this library, and the JsonMapper type is built on top of them, so in a way, the developer can think of the reader and writer classes as the low–level programming interface for LitJSON.

Using JsonReader

  1. using LitJson;
  2. using System;
  3. public class DataReader
  4. {
  5. public static void Main()
  6. {
  7. string sample = @"{
  8. ""name"" : ""Bill"",
  9. ""age"" : 32,
  10. ""awake"" : true,
  11. ""n"" : 1994.0226,
  12. ""note"" : [ ""life"", ""is"", ""but"", ""a"", ""dream"" ]
  13. }";
  14. PrintJson(sample);
  15. }
  16. public static void PrintJson(string json)
  17. {
  18. JsonReader reader = new JsonReader(json);
  19. Console.WriteLine ("{0,14} {1,10} {2,16}", "Token", "Value", "Type");
  20. Console.WriteLine (new String ('-', 42));
  21. // The Read() method returns false when there's nothing else to read
  22. while (reader.Read()) {
  23. string type = reader.Value != null ?
  24. reader.Value.GetType().ToString() : "";
  25. Console.WriteLine("{0,14} {1,10} {2,16}",
  26. reader.Token, reader.Value, type);
  27. }
  28. }
  29. }

This example would produce the following output:

  1. Token Value Type
  2. ------------------------------------------
  3. ObjectStart
  4. PropertyName name System.String
  5. String Bill System.String
  6. PropertyName age System.String
  7. Int 32 System.Int32
  8. PropertyName awake System.String
  9. Boolean True System.Boolean
  10. PropertyName n System.String
  11. Double 1994.0226 System.Double
  12. PropertyName note System.String
  13. ArrayStart
  14. String life System.String
  15. String is System.String
  16. String but System.String
  17. String a System.String
  18. String dream System.String
  19. ArrayEnd
  20. ObjectEnd

Using JsonWriter

The JsonWriter class is quite simple. Keep in mind that if you want to convert some arbitrary object into a JSON string, you’d normally just use JsonMapper.ToJson.

  1. using LitJson;
  2. using System;
  3. using System.Text;
  4. public class DataWriter
  5. {
  6. public static void Main()
  7. {
  8. StringBuilder sb = new StringBuilder();
  9. JsonWriter writer = new JsonWriter(sb);
  10. writer.WriteArrayStart();
  11. writer.Write(1);
  12. writer.Write(2);
  13. writer.Write(3);
  14. writer.WriteObjectStart();
  15. writer.WritePropertyName("color");
  16. writer.Write("blue");
  17. writer.WriteObjectEnd();
  18. writer.WriteArrayEnd();
  19. Console.WriteLine(sb.ToString());
  20. }
  21. }

Output from the example:

  1. [1,2,3,{"color":"blue"}]

Configuring the library’s behaviour

JSON is a very concise data–interchange format; nothing more, nothing less. For this reason, handling data in JSON format inside a program may require a deliberate decision on your part regarding some little detail that goes beyond the scope of JSON’s specs.

Consider, for example, reading data from JSON strings where single–quotes are used to delimit strings, or Javascript–style comments are included as a form of documentation. Those things are not part of the JSON standard, but they are commonly used by some developers, so you may want to be forgiving or strict depending on the situation. Or what about if you want to convert a .Net object into a JSON string, but pretty–printed (using indentation)?

To declare the behaviour you want, you may change a few properties from your JsonReader and JsonWriter objects.

Configuration of JsonReader

  1. using LitJson;
  2. using System;
  3. public class JsonReaderConfigExample
  4. {
  5. public static void Main()
  6. {
  7. string json;
  8. json = " /* these are some numbers */ [ 2, 3, 5, 7, 11 ] ";
  9. TestReadingArray(json);
  10. json = " [ \"hello\", 'world' ] ";
  11. TestReadingArray(json);
  12. }
  13. static void TestReadingArray(string json_array)
  14. {
  15. JsonReader defaultReader, customReader;
  16. defaultReader = new JsonReader(json_array);
  17. customReader = new JsonReader(json_array);
  18. customReader.AllowComments = false;
  19. customReader.AllowSingleQuotedStrings = false;
  20. ReadArray(defaultReader);
  21. ReadArray(customReader);
  22. }
  23. static void ReadArray(JsonReader reader)
  24. {
  25. Console.WriteLine("Reading an array");
  26. try {
  27. JsonData data = JsonMapper.ToObject(reader);
  28. foreach (JsonData elem in data)
  29. Console.Write(" {0}", elem);
  30. Console.WriteLine(" [end]");
  31. }
  32. catch (Exception e) {
  33. Console.WriteLine(" Exception caught: {0}", e.Message);
  34. }
  35. }
  36. }

The output would be:

  1. Reading an array
  2. 2 3 5 7 11 [end]
  3. Reading an array
  4. Exception caught: Invalid character '/' in input string
  5. Reading an array
  6. hello world [end]
  7. Reading an array
  8. Exception caught: Invalid character ''' in input string

Configuration of JsonWriter

  1. using LitJson;
  2. using System;
  3. public enum AnimalType
  4. {
  5. Dog,
  6. Cat,
  7. Parrot
  8. }
  9. public class Animal
  10. {
  11. public string Name { get; set; }
  12. public AnimalType Type { get; set; }
  13. public int Age { get; set; }
  14. public string[] Toys { get; set; }
  15. }
  16. public class JsonWriterConfigExample
  17. {
  18. public static void Main()
  19. {
  20. var dog = new Animal {
  21. Name = "Noam Chompsky",
  22. Type = AnimalType.Dog,
  23. Age = 3,
  24. Toys = new string[] { "rubber bone", "tennis ball" }
  25. };
  26. var cat = new Animal {
  27. Name = "Colonel Meow",
  28. Type = AnimalType.Cat,
  29. Age = 5,
  30. Toys = new string[] { "cardboard box" }
  31. };
  32. TestWritingAnimal(dog);
  33. TestWritingAnimal(cat, 2);
  34. }
  35. static void TestWritingAnimal(Animal pet, int indentLevel = 0)
  36. {
  37. Console.WriteLine("\nConverting {0}'s data into JSON..", pet.Name);
  38. JsonWriter writer1 = new JsonWriter(Console.Out);
  39. JsonWriter writer2 = new JsonWriter(Console.Out);
  40. writer2.PrettyPrint = true;
  41. if (indentLevel != 0)
  42. writer2.IndentValue = indentLevel;
  43. Console.WriteLine("Default JSON string:");
  44. JsonMapper.ToJson(pet, writer1);
  45. Console.Write("\nPretty-printed:");
  46. JsonMapper.ToJson(pet, writer2);
  47. Console.WriteLine("");
  48. }
  49. }

The output from this example is:


  1. Converting Noam Chompsky's data into JSON..
  2. Default JSON string:
  3. {"Name":"Noam Chompsky","Type":0,"Age":3,"Toys":["rubber bone","tennis ball"]}
  4. Pretty-printed:
  5. {
  6. "Name" : "Noam Chompsky",
  7. "Type" : 0,
  8. "Age" : 3,
  9. "Toys" : [
  10. "rubber bone",
  11. "tennis ball"
  12. ]
  13. }
  14. Converting Colonel Meow's data into JSON..
  15. Default JSON string:
  16. {"Name":"Colonel Meow","Type":1,"Age":5,"Toys":["cardboard box"]}
  17. Pretty-printed:
  18. {
  19. "Name" : "Colonel Meow",
  20. "Type" : 1,
  21. "Age" : 5,
  22. "Toys" : [
  23. "cardboard box"
  24. ]
  25. }

LitJSON使用的更多相关文章

  1. 在引用KindEditor编辑器时,运行时出现以下错误:错误46 找不到类型或命名空间名称“LitJson”(是否缺少 using 指令或程序集引用?)

    将asp.net下bin文件夹下的文件LitJSON.dll拷贝到工程的bin目录下,并在工程中添加引用 在后台加入: using LitJson;

  2. 关于litJson的System.InvalidCastException

    最近在做一个Unity3D的项目,用到了litJson库, 它比JavaScript里的JSON解析更加严格, 有时候解析数据的时候会出现类型不对. 比如说 {"data":12} ...

  3. XML数据 JSON数据 LitJSON 数据 的编写和解析 小结

    用XML生成如下数据<?xml version="1.0"encoding="UTF-8"?><Transform name="My ...

  4. 【Unity3D插件】在Unity中读写文件数据:LitJSON快速教程

    作者:王选易,出处:http://www.cnblogs.com/neverdie/ 欢迎转载,也请保留这段声明.如果你喜欢这篇文章,请点[推荐].谢谢! 介绍 JSON是一个简单的,但功能强大的序列 ...

  5. (转)LitJson 遍历key

    本文转载自:http://blog.csdn.net/inlet511/article/details/47127579 用LitJson插件获取到的对象,如果想遍历对象中包含的子对象的key,可以用 ...

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

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

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

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

  8. LitJson处理Json

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

  9. LitJson解析遇到的坑

    今天在些项目的时候,遇到一个坑,现在跟大家分享一下 我遇到的错误是MissingMethodException: Method not found: 'Default constructor not ...

随机推荐

  1. poll机制分析

    更多文档:http://pan.baidu.com/s/1sjzzlDF linux poll/select用法及在字符驱动中的简单实现 1.poll和select 使用非阻塞I/O 的应用程序常常使 ...

  2. Working with MTD Devices

    转:http://www.linuxforu.com/2012/01/working-with-mtd-devices/ Working with MTD Devices By Mohan Lal J ...

  3. spark1.2.0安装

    standalone 安装SCALA 下载.解压.加入环境变量 安装spark1.2.0 下载.解压.加入环境变量 tar zxvf spark--bin-.tgz export SPARK_HOME ...

  4. JavaScript 获取当前时间戳的代码

    avaScript 获取当前时间戳: 第一种方法: 复制代码代码如下: var timestamp = Date.parse(new Date());  结果:1280977330000 第二种方法: ...

  5. [SEO] 网站标题分隔符

    标题用什么分隔符对SEO最有利 我们在看同行的朋友对网站标题优化时,关键词分按照主次的顺序进行分布,在网站标题或者是关键词之间都会有一个符号,俗话来讲就称为关键词分隔符,网站标 题分隔符分为“-”(横 ...

  6. Unity封装dll教程整理

    ///作者Unity3d师兄---LeroyYang 通过网上大神们的资料以及自己的整理,学习一下用vs2013简单的封装dll文件,方便接口模式下开发,使得逻辑层更为清晰. 操作步骤 1.打开vs2 ...

  7. <c:forEach> 详解

    <c:forEach>标签用于通用数据循环,它有以下属性 属 性 描 述 是否必须 缺省值 items 进行循环的项目 否 无 begin 开始条件 否 0 end 结束条件 否 集合中的 ...

  8. 【安卓面试题】Activity和Task的启动模式有哪些?每种含义是什么?举例说明各自的应用场景

    Activity和Task的启动模式有哪些?每种含义是什么?举例说明各自的应用场景 Activity的启动模式 (Launchmode) 有4种 1.standard 默认模式,不需要配置 含义: 启 ...

  9. 剑指Offer35 两个链表第一个公共结点

    /************************************************************************* > File Name: 35_FirstC ...

  10. python 打包exe注意的问题

    教程百度.谷歌都有,本文讲讲安装时出错的问题. 教程:http://keliang.blog.51cto.com/3359430/661884 1.cxfreeze 找不到路径时: 需要修改Scrip ...