LitJson github:  传送门

  JsonUtility创建和解析Json  传送门

  LitJson.dll百度云盘  传送门  密码:p1py  

  

  加载LitJson.dll到Unity中

  在Assets文件夹下创建一个Plugins文件(文件名不得有错),把LitJson.dll放进去

  新建一个LitJson_Gary.cs脚本,挂在到GameObject上

Unity3D_(数据)LitJson创建和解析Json

 

 

第一种使用LitJson创建和解析Json

  好处:逻辑清晰,适用于稍微复杂的Json类型,适用于层级复杂情况

  坏处:需要单独写类,写的代码稍微多一些

Unity3D_(数据)LitJson创建和解析Json

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;

public class Hero
{
    public string name;
    public int power;
}

public class Heros
{
    public Hero[] heros;
}

public class LitJson_Gary : MonoBehaviour {

    // Use this for initialization
    void Start () {
        func1();
    }
    
    void func1()
    {
        //创建Json
        //{'heros':[{'name':'Gary','power':90},{'name':'Gary2','power':80}]}

        Hero hero1 = new Hero();
        hero1.name = "Gary";
        hero1.power = 90;
        Hero hero2 = new Hero();
        hero2.name = "Gary2";
        hero2.power = 80;

        Heros heros = new Heros();
        heros.heros = new Hero[] {hero1,hero2};

        string jsonStr = JsonMapper.ToJson(heros);
        Debug.Log(jsonStr);

        //解析Json
        Heros newHeros = JsonMapper.ToObject<Heros>(jsonStr);
        Debug.Log(newHeros.heros[0].name);

    }
}
LitJson_Gary.cs

相关文章: