Unity中JsonUtility对List和Dictionary的序列化

Unity5.3从开始追加的JsonUtility,但是对于List 和Dictionary不能被直接序列化存储


例如: 

数据模型

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

[Serializable]
public class Enemy
{
    [SerializeField]
    string name;
    [SerializeField]
    List skills;

    public Enemy(string name, List skills)
    {
        this.name = name;
        this.skills = skills;
    }
}
实际使用


List enemies = new List();
enemies.Add(new Enemy("怪物1", new List() { "攻击" }));
enemies.Add(new Enemy("怪物2", new List() { "攻击", "恢复" }));
Debug.Log(JsonUtility.ToJson(enemies));

输出为:{}

输出是没有任何的json字符串。


在unity的官方网站,I SerializationCallbackReceiver继承的方法被提出,


// Serialization.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

// List
[Serializable]
public class Serialization
{
    [SerializeField]
    List target;
    public List ToList() { return target; }

    public Serialization(List target)
    {
        this.target = target;
    }
}

// Dictionary
[Serializable]
public class Serialization : ISerializationCallbackReceiver
{
    [SerializeField]
    List keys;
    [SerializeField]
    List values;

    Dictionary target;
    public Dictionary ToDictionary() { return target; }

    public Serialization(Dictionary target)
    {
        this.target = target;
    }

    public void OnBeforeSerialize()
    {
        keys = new List(target.Keys);
        values = new List(target.Values);
    }

    public void OnAfterDeserialize()
    {
        var count = Math.Min(keys.Count, values.Count);
        target = new Dictionary(count);
        for (var i = 0; i < count; ++i)
        {
            target.Add(keys[i], values[i]);
        }
    }
}

使用


// List -> Json ( 例 : List )
string str = JsonUtility.ToJson(new Serialization(enemies)); // 输出 : {"target":[{"name":"怪物1,"skills":["攻击"]},{"name":"怪物2","skills":["攻击","恢复"]}]}
// Json-> List
List enemies = JsonUtility.FromJson>(str).ToList();

// Dictionary -> Json( 例 : Dictionary )
string str = JsonUtility.ToJson(new Serialization(enemies)); // 输出 : {"keys":[1000,2000],"values":[{"name":"怪物1","skills":["攻击"]},{"name":"怪物2","skills":["攻击","恢复"]}]}
// Json -> Dictionary
Dictionary enemies = JsonUtility.FromJson>(str).ToDictionary();



你可能感兴趣的:(Unity3D)