Unity Json 之三

今天在网上看到一个simplejson,直接调用这两个API就可以了,简单易用

string jsonstr = SimpleJson.SimpleJson.SerializeObject(json);
Debug.LogError(jsonstr);
TestJson test = SimpleJson.SimpleJson.DeserializeObject<TestJson>(jsonstr);

做了测试和JsonUtility.ToJson(json);几乎是一样的,但是JsonUtility.ToJson(json); 需要在每个类上加上[System.Serializable] 特性标签 ,并且只能用字段,不能用属性 ,都可以满足我们日常需求

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

[System.Serializable]
public class TestJson
{
    [SerializeField] //经测试,加不加都可以
    public string Name;
    [SerializeField]
    public Student[] stud;
}
[System.Serializable]
public class Student
{
    [SerializeField]
    public string School;
    [SerializeField]
    public Gender gender;
}

[System.Serializable]
public class Gender
{
    [SerializeField]
    public int age;
    [SerializeField]
    public List<int> list;
}



public class TestSimpliJson : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {
        Tess();
    }
    void Tess()
    {
        TestJson json = new TestJson();
        json.Name = "飞天小猪";
        json.stud = new Student[4];

        for (int i = 0; i < json.stud.Length; i++)
        {
            json.stud[i] = new Student();
            json.stud[i].School = "飞天小猪" + i;
            json.stud[i].gender = new Gender();
            json.stud[i].gender.age = i;
            json.stud[i].gender.list = new List<int>();
            for (int j = 0; j < i * i; j++)
            {
                json.stud[i].gender.list.Add(j);
            }
        }

        string jsonstr = SimpleJson.SimpleJson.SerializeObject(json);
        Debug.LogError(jsonstr);
        TestJson test = SimpleJson.SimpleJson.DeserializeObject<TestJson>(jsonstr);
        string strJson = JsonUtility.ToJson(json);
        Debug.LogError(strJson);
    }
}

 

两种方式,输出如下

{"Name":"飞天小猪","stud":[{"School":"飞天小猪0","gender":{"age":0,"list":[]}},{"School":"飞天小猪1","gender":{"age":1,"list":[0]}},{"School":"飞天小猪2","gender":{"age":2,"list":[0,1,2,3]}},{"School":"飞天小猪3","gender":{"age":3,"list":[0,1,2,3,4,5,6,7,8]}}]}

 

 不过如果不给list赋值,稍微有点不一样的地方

{"Name":"飞天小猪","stud":[{"School":"飞天小猪0","gender":{"age":0,"list":null}},{"School":"飞天小猪1","gender":{"age":1,"list":null}},{"School":"飞天小猪2","gender":{"age":2,"list":null}},{"School":"飞天小猪3","gender":{"age":3,"list":null}}]}

 

{"Name":"飞天小猪","stud":[{"School":"飞天小猪0","gender":{"age":0,"list":[]}},{"School":"飞天小猪1","gender":{"age":1,"list":[]}},{"School":"飞天小猪2","gender":{"age":2,"list":[]}},{"School":"飞天小猪3","gender":{"age":3,"list":[]}}]}

 

posted @ 2017-12-02 15:13  飞天艾特小猪  阅读(276)  评论(0编辑  收藏  举报