地址: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.

using LitJson;
using System; public class Person
{
// C# 3.0 auto-implemented properties
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
} public class JsonSample
{
public static void Main()
{
PersonToJson();
JsonToPerson();
} public static void PersonToJson()
{
Person bill = new Person(); bill.Name = "William Shakespeare";
bill.Age = 51;
bill.Birthday = new DateTime(1564, 4, 26); string json_bill = JsonMapper.ToJson(bill); Console.WriteLine(json_bill);
} public static void JsonToPerson()
{
string json = @"
{
""Name"" : ""Thomas More"",
""Age"" : 57,
""Birthday"" : ""02/07/1478 00:00:00""
}"; Person thomas = JsonMapper.ToObject<Person>(json); Console.WriteLine("Thomas' age: {0}", thomas.Age);
}
}

Output from the example:

{"Name":"William Shakespeare","Age":51,"Birthday":"04/26/1564 00:00:00"}
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.

using LitJson;
using System; public class JsonSample
{
public static void Main()
{
string json = @"
{
""album"" : {
""name"" : ""The Dark Side of the Moon"",
""artist"" : ""Pink Floyd"",
""year"" : 1973,
""tracks"" : [
""Speak To Me"",
""Breathe"",
""On The Run""
]
}
}
"; LoadAlbumData(json);
} public static void LoadAlbumData(string json_text)
{
Console.WriteLine("Reading data from the following JSON string: {0}",
json_text); JsonData data = JsonMapper.ToObject(json_text); // Dictionaries are accessed like a hash-table
Console.WriteLine("Album's name: {0}", data["album"]["name"]); // Scalar elements stored in a JsonData instance can be cast to
// their natural types
string artist = (string) data["album"]["artist"];
int year = (int) data["album"]["year"]; Console.WriteLine("Recorded by {0} in {1}", artist, year); // Arrays are accessed like regular lists as well
Console.WriteLine("First track: {0}", data["album"]["tracks"][0]);
}
}

Output from the example:

Reading data from the following JSON string:
{
"album" : {
"name" : "The Dark Side of the Moon",
"artist" : "Pink Floyd",
"year" : 1973,
"tracks" : [
"Speak To Me",
"Breathe",
"On The Run"
]
}
} Album's name: The Dark Side of the Moon
Recorded by Pink Floyd in 1973
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

using LitJson;
using System; public class DataReader
{
public static void Main()
{
string sample = @"{
""name"" : ""Bill"",
""age"" : 32,
""awake"" : true,
""n"" : 1994.0226,
""note"" : [ ""life"", ""is"", ""but"", ""a"", ""dream"" ]
}"; PrintJson(sample);
} public static void PrintJson(string json)
{
JsonReader reader = new JsonReader(json); Console.WriteLine ("{0,14} {1,10} {2,16}", "Token", "Value", "Type");
Console.WriteLine (new String ('-', 42)); // The Read() method returns false when there's nothing else to read
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);
}
}
}

This example would produce the following output:

         Token      Value             Type
------------------------------------------
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

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.

using LitJson;
using System;
using System.Text; public class DataWriter
{
public static void Main()
{
StringBuilder sb = new 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());
}
}

Output from the example:

[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

using LitJson;
using System; public class JsonReaderConfigExample
{
public static void Main()
{
string json; json = " /* these are some numbers */ [ 2, 3, 5, 7, 11 ] ";
TestReadingArray(json); json = " [ \"hello\", 'world' ] ";
TestReadingArray(json);
} static void TestReadingArray(string json_array)
{
JsonReader defaultReader, customReader; defaultReader = new JsonReader(json_array);
customReader = new JsonReader(json_array); customReader.AllowComments = false;
customReader.AllowSingleQuotedStrings = false; ReadArray(defaultReader);
ReadArray(customReader);
} static void ReadArray(JsonReader reader)
{
Console.WriteLine("Reading an array"); try {
JsonData data = JsonMapper.ToObject(reader); foreach (JsonData elem in data)
Console.Write(" {0}", elem); Console.WriteLine(" [end]");
}
catch (Exception e) {
Console.WriteLine(" Exception caught: {0}", e.Message);
}
}
}

The output would be:

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

Configuration of JsonWriter

using LitJson;
using System; public enum AnimalType
{
Dog,
Cat,
Parrot
} public class Animal
{
public string Name { get; set; }
public AnimalType Type { get; set; }
public int Age { get; set; }
public string[] Toys { get; set; }
} public class JsonWriterConfigExample
{
public static void Main()
{
var dog = new Animal {
Name = "Noam Chompsky",
Type = AnimalType.Dog,
Age = 3,
Toys = new string[] { "rubber bone", "tennis ball" }
}; var cat = new Animal {
Name = "Colonel Meow",
Type = AnimalType.Cat,
Age = 5,
Toys = new string[] { "cardboard box" }
}; TestWritingAnimal(dog);
TestWritingAnimal(cat, 2);
} static void TestWritingAnimal(Animal pet, int indentLevel = 0)
{
Console.WriteLine("\nConverting {0}'s data into JSON..", pet.Name);
JsonWriter writer1 = new JsonWriter(Console.Out);
JsonWriter writer2 = new JsonWriter(Console.Out); writer2.PrettyPrint = true;
if (indentLevel != 0)
writer2.IndentValue = indentLevel; Console.WriteLine("Default JSON string:");
JsonMapper.ToJson(pet, writer1); Console.Write("\nPretty-printed:");
JsonMapper.ToJson(pet, writer2);
Console.WriteLine("");
}
}

The output from this example is:


Converting Noam Chompsky's data into JSON..
Default JSON string:
{"Name":"Noam Chompsky","Type":0,"Age":3,"Toys":["rubber bone","tennis ball"]}
Pretty-printed:
{
"Name" : "Noam Chompsky",
"Type" : 0,
"Age" : 3,
"Toys" : [
"rubber bone",
"tennis ball"
]
} Converting Colonel Meow's data into JSON..
Default JSON string:
{"Name":"Colonel Meow","Type":1,"Age":5,"Toys":["cardboard box"]}
Pretty-printed:
{
"Name" : "Colonel Meow",
"Type" : 1,
"Age" : 5,
"Toys" : [
"cardboard box"
]
}

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. PHP header 的几种用法

    跳转页面 header('Location:'.$url); //Location和":"之间无空格. 声明content-type header('content-type:te ...

  2. 学java入门到精通,不得不看的15本书

    学java入门到精通,不得不看的15本书 一.Java编程入门类1.<Java编程思想>2.<Agile Java>中文版 二.Java编程进阶类1.<重构 改善既有代码 ...

  3. Ubuntu上手动安装nginx

    最近需要利用nginx上搭建一个网站,因此在自己的电脑上安装了nginx,现在分享一下自己在安装过程及遇到的问题. 1.下载需要的nginx版本的安装包. axel -n http://nginx.o ...

  4. .NET多线程执行函数

    前面几篇文章一直在写LINQ,这里为什么会出现多线程?原因是DebugLZQ在写一个LINQ综合Demo的时候遇到了多线程,便停下手来整理一下.关于多线程的文章,园子里很多很多,因此关于多线程理论性的 ...

  5. Android自定义控件:进度条的四种实现方式(Progress Wheel的解析)

    最近一直在学习自定义控件,搜了许多大牛们Blog里分享的小教程,也上GitHub找了一些类似的控件进行学习.发现读起来都不太好懂,就想写这么一篇东西作为学习笔记吧. 一.控件介绍: 进度条在App中非 ...

  6. 使用 sp_executesql

    建议您在执行字符串时,使用 sp_executesql 存储过程而不要使用 EXECUTE 语句.由于此存储过程支持参数替换,因此 sp_executesql 比 EXECUTE 的功能更多:由于 S ...

  7. CSS3: border-radius边框圆角详解

    border-radius 基本语法: border-radius : none | <length>{1,4} [/ <length>{1,4} ]? 取值范围: <l ...

  8. JQuery总结:选择器归纳、DOM遍历和事件处理、DOM完全操作和动画 (转)

    JQuery总结:选择器归纳.DOM遍历和事件处理.DOM完全操作和动画 转至元数据结尾 我们后台可能用到的页面一般都是用jquery取值赋值的,发现一片不错的文章 目录 JQuery总结一:选择器归 ...

  9. Linux Bash Shell学习笔记

    参数扩展: 1.被名称引用的参数称作变量2.被数字引用的参数称作位置参数3.被特定符号引用的参数具有特殊的含义和用途,被称作Bash的特殊内部变量引用. 基本参数扩展:字符$会引导参数扩展.大括号是可 ...

  10. hdu 1530 最大团模板

    说明摘自:pushing my way 的博文 最大团 通过该博主的代码,总算理解了最大团问题,但是他实现时的代码效率却不算太高.因此在最后献上我的模板.加了IO优化目前的排名是: 6 yejinru ...