"Go" read and write file data in Unity: Litjson Quick Tutorial

Source: Internet
Author: User
Tags tojson

Wang Xuan Yi, Source: http://www.cnblogs.com/neverdie/ Welcome reprint , please also keep this paragraph statement. If you like this article, please click "Recommend". Thank you!

Introduction

JSON is a simple, but powerful, serialized data format. It defines simple types, such as Boolean, number (int and float), and string, and several data structures: List and dictionnary. You can learn more about JSON in http://JSON.org.

Litjson is used in C #编写的, it is intended to be small, fast, and easy to use. It uses the Mono framework.

Installing Litjson

The Litjson compiled DLL file is imported into the project by importing New asset, and the use Litjson can be used to use the easy method in the Jsonmapper class. DLL's here.

convert JSON to an object and reverse conversion

In order to be in. NET program uses JSON-formatted data. A natural approach is to use JSON literals to generate a new instance of a particular class, and to match the format of the class, the generally stored JSON string is a dictionary.

On the other hand, in order to serialize an object into a JSON string, a simple export operation sounds a good idea.

For this purpose, the Litjson package introduces the Jsonmapper class, which provides two primary methods for converting JSON to object and object to JSON. These two methods are Jsonmapper.toobject and Jsonmapper.tojson.

After the object is converted to a string, we can easily read and write the string in the file.

An example of a simple jsonmapper

In the following example, the Toobject method has a generic parameter that specifies a specific data type that is returned: jsonmapper.toobject<t>.

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 Mo        Re "", "" Age "": "," "Birthday" ":" "02/07/1478 00:00:00" "}";        Person Thomas = jsonmapper.toobject<person> (JSON); Console.WriteLine ("Thomas ' Age: {0}", Thomas.    Age); }}

The output above:

{"Name": "William Shakespeare", "Age": Wuyi, "Birthday": "04/26/1564 00:00:00"} Thomas ' age:57
using non-generic jsonmapper.toobject

When there is no specific JSON data class, it returns a Jsondata instance. Jsondata is a generic type that can hold any data type supporting JSON, including list and dictionary.

Using litjson;using System;public class jsonsample{public static void Main () {String json = @ "{               "Album" ": {" "" "" "" "" "Dark Side of the Moon" "," "Artist" ":" "Pink Floyd" ",        "On the Run" "]}}";    Loadalbumdata (JSON); } public static void Loadalbumdata (String json_text) {Console.WriteLine ("Reading data from the following JSO        N string: {0} ", Json_text);        Jsondata data = Jsonmapper.toobject (Json_text);        Dictionaries is accessed like a hash-table Console.WriteLine ("Album ' s name: {0}", data["Album" ["name"]); Scalar elements stored in a Jsondata instance can is cast to//their natural types string artist = (s        Tring) data["album" ["Artist"];   Int Year = (int) data["album" ["Year"];        Console.WriteLine ("Recorded by {0} in {1}", artist, year); Arrays is accessed like regular lists as well Console.WriteLine ("first track: {0}", data["album" ["Tracks"][0])    ; }}

The output of the above example:

Reading data from the following JSON string:          {"            album": {"              name"   : "The Dark Side of the Moon",              "Arti St ":" Pink Floyd ",              " Year "   : 1973,              " tracks ": [                " Speak to Me ",                " Breathe ",                " on the Run "              ]            }          } Album ' s name:the Dark Side of the moonrecorded by Pink Floyd in 1973First track:speak to Me
Reader and writer

Some people like to use stream to process JSON data, and for them, the interfaces we provide are jsonreader and jsonwriter.

Jsonmapper is actually based on the above two classes, so you can think of these two classes as Litjson's underlying interface.

using Jsonreader
 using litjson;using system;public class datareader{public static void Main () {            String sample = @ "{" "Name" ":" "Bill" "," "Age" ":", "" Awake ": true,        "N" ": 1994.0226," "Note" ": [" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "";    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); }    }}

The output is as follows:

Token      Value             Type------------------------------------------   objectstart                              PropertyName       Name    System.String        String       Bill    System.String  PropertyName        age    System.String           Int     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
An example of installing Litjson to convert JSON to object and reverse-convert a simple jsonmapper using non-generic Jsonmapper.toobjectreader and writer uses jsonreaderHide Directory

"Go" read and write file data in Unity: Litjson Quick Tutorial

Related Article

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.