Unity JSON parsing <一> -read JSON file __js

Source: Internet
Author: User
Tags serialization static class tojson

This article written by Cartzhang, reproduced please indicate the source. All rights reserved.
Article Link: http://blog.csdn.net/cartzhang/article/details/50373558
Author: Cartzhang Unity JSON Parsing < A >– read JSON file

Because you need to do an external file configuration, consider XML and JSON, and the 5.3 version of JSON is updated, so just try it.
Introduction to the JSON section of the version update OH: [Unity5.3 version updated JSON section]

Https://github.com/cartzhang/UnityJsonTest/blob/master/Assets/JSONSerialization.html

https://unity3d.com/cn/unity/whats-new/unity-5.3

Online editing of https://blogs.unity3d.com/cn/2015/12/08/unity-5-3-all-new-features-and-more-platforms/JSON

Json parser:http://json.parser.online.fr/
JSON online EDIT: http://www.kjson.com/jsoneditor/?f=1

The second is a direct download to save to the local, this operation is very good. jsonutility

First of all, in unity, we are in the JSON tool class, the available functions, a total of 5, how much less ah. However, the simple is better.

#region Assembly Unityengine, version=0.0.0.0, culture=neutral, publickeytoken=null//H:\Unity\Project\JsonReadTest\

Library\unityassemblies\unityengine.dll #endregion using System;
    namespace Unityengine {////Summary:///////Utility functions for working with JSON data.  public static class Jsonutility {////Summary:///////Create
        Object from its JSON representation.
        ///Parameter://JSON://The JSON representation of the object.
        Type://The type of object represented by the JSON.
        Return Result:///////An instance of the object.
        [Wrapperlessicall] public static object Fromjson (string json, type type);
        public static T fromjson<t> (string json); Absrtact:///////Overwrite data in a OBject by reading to its JSON representation.
        ///Parameter://JSON://The JSON representation of the object.
        Objecttooverwrite://The object that should is overwritten.
        [Wrapperlessicall] public static void Fromjsonoverwrite (String json, Object objecttooverwrite);
        Summary:///////Generate A JSON representation of the public fields of.
        ///parameter://obj://The object to convert to JSON form. Prettyprint://If True, format the output for readability. If false, format the output for minimum//size.
        The Default is false.
        Return Result:///////The object ' s data in JSON format.
        public static string Tojson (object obj);
  Summary://///      Generate a JSON representation of the ' public fields of ' an object.
        ///parameter://obj://The object to convert to JSON form. Prettyprint://If True, format the output for readability. If false, format the output for minimum//size.
        The Default is false.
        Return Result:///////The object ' s data in JSON format.
    [Wrapperlessicall] public static string Tojson (object obj, bool prettyprint); }
}

As you can see, the main thing is to create two types of objects and into JSON format. preparatory work

We need a JSON file, this is the protagonist Ah, is to read its content AH.
All right. I wrote a random, named Test.json placed in my. \assets\resources\ directory;
The contents of the JSON file are as follows:

{"Gamename": "JSON serializer Test", "Version": "1.0", "Isstereo": "false", "Isusehardware": "true", "statuslist": [{] Name ': ' Test ', ' id ': ' 1u702 '}]}
creating an Object class

First, we need to create an object class that holds the content read from the JSON text.
Give this class a name of GameStatus.cs

Using Unityengine;
Using System;
Using System.Collections;

[Serializable]
public class GameStatus
{public
    string gamename;
    public string version;
    public bool Isstereo;
    public bool Isusehardware;
    Public refencenes[] statuslist;
}

[Serializable]
public class Refencenes
{public
    string name;
    public int id;
}

requires a read class

This write a static class, you can also add the written content
Name is LoadJson.cs

Using Unityengine;
Using System.Collections;
Using System.IO;

Using System.Runtime.Serialization.Formatters.Binary;  public class Loadjson:monobehaviour {public static gamestatus Loadjsonfromfile () {BinaryFormatter BF =

        New BinaryFormatter (); if (!
        File.exists (Application.datapath + "/resources/test.json")) {return null;

        StreamReader sr = new StreamReader (Application.datapath + "/resources/test.json");
        FileStream file = File.Open (Application.datapath + "/test.json", FileMode.Open, FileAccess.ReadWrite); if (file.
        Length = = 0)//{//return null; //string json = (string) bf.
        Deserialize (file); File.

        Close ();
        if (sr = null) {return null; } string json = Sr.

        ReadToEnd (); if (JSON.
        Length > 0) {return jsonutility.fromjson<gamestatus> (JSON);
  return null;  }
}


 

Description: The code is commented out of the section, is found from the Internet, parse JSON into binary format, and then deserialized into a string, the result, may be coding format problems, not correct deserialization, always error.
I expressed helplessness, had to use the StreamReader from the realism to deal with. Call

The call is quite simple, in the update, using the L key to load the JSON file.
The code is as follows:

Using Unityengine;
Using System.Collections;
Using System;
Using System.Runtime.Serialization.Formatters.Binary;
Using System.IO;

public class Readjson:monobehaviour
{

    void  Update ()
    {
        if (Input.getkeydown (KEYCODE.S)
        ) {
            //save ();
        }

        if (Input.getkeydown (KEYCODE.L))
        {
            GameStatus status = Loadjson.loadjsonfromfile ();
            Debug.Log (status);}}


Test Results

In the scene, create an empty object, and then drag the Readjson onto the object, run, press the L key, you can use breakpoints to view, of course, log output.

The results are shown below:

Description

The overall process is simple. The project will not be uploaded.

If you have any questions, please feel free to contact.
Thank you so much.

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.