[C # technology] How to Use LitJSON, an open-source JSON library on the. NET platform

Source: Internet
Author: User
Tags tojson

A simple example:

String str = "{'name': 'cyf', 'id': 10, 'items ': [{'itemid': 1001, 'itemname': 'hello '}, {'itemid': 1002, 'itemname': 'hello2'}]} ";
****************************** *
JsonData jd = JsonMapper. ToObject (str );
String name = (String) jd ["name"];
Long id = (long) jd ["id"];
JsonData jdItems = jd ["items"];
Int itemCnt = jdItems. Count;
// Number of items in the array items
Foreach (JsonData item in jdItems)
// Traverse the array items
{Int itemID = (int) item ["itemid"];
String itemName = (String) item ["itemname"];
}

// *** Convert JsonData to a JSON string ***************************

String str2 = jd. ToJson ();

: Download

LitJSON is a class library that processes JSON data on the. NET platform. It is small and fast. Its source code is written in C # and can be called in any language on the. Net platform. The latest version is LitJSON 0.5.0.

Compared with the open-source JSON libraries on the following. Net platforms, LitJSON is far ahead in performance:

Jayrock version 0.9.8316

LitJSON version 0.3.0

Newtonsoft Json. NET version 1.1

The following describes the commonly used methods in LitJSON:

In the following example, you must first add the reference LitJson. dll and then import the namespace using LitJson;

Click to download LitJSON. dll directly, you can also go to the http://litjson.sourceforge.net to download.

1. Conversion of object objects in Json and C #

Example 1.1: Use the JsonMapper class to convert data

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 ();
}
///
/// Convert the object class to Json format
///
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 );
// Output: {"Name": "www.87cool.com", "Age": 3, "Birthday": "07/17/2007 00:00:00 "}
}

///
/// Convert Json data into Entity classes
///
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 );
// Output: '87cool 'age: 3
}
}

Example 1.2: Use the JsonMapper class to convert a Json string to JsonData recognized by C #, and then obtain the value through the Json data attribute name or index.

Reading JsonData objects in C # is the same as reading Json objects in JavaScript;

This reading method for Json is very nice and practical in C #, because the data returned by APIs provided by many network applications is in Json format,

For example, data in json format is returned by the photo album API of Flickr.
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. Readers and Writers of Json in C #

Example 2.1: How to Use the JsonReader class
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 );
}
// Output all Json data types and values
Public static void ReadJson (string json)
{
JsonReader reader = new JsonReader (json );

Console. WriteLine ("{}", "Token", "Value", "Type ");
Console. WriteLine (new String ('-', 42 ));
While (reader. Read ())
{
String type = reader. Value! = Null? Reader. Value. GetType (). ToString ():"";
Console. WriteLine ("{}", reader. Token, reader. Value, type );
}
}
}

// Output result:

// Json type value C # 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

Example 2.2: How to Use the JsonWriter class
Public class DataReader
{
// Create a Json object through the JsonWriter class
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 ());
// Output: [1, 2, 3, {"color": "blue"}]
}
}

For more details, refer to http://litjson.sourceforge.net/doc/manual.html)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.