Json JsonUtility對字典/列表的序列化,反序列化


Unity5.3從開始追加的JsonUtility,但是對於List 和Dictionary不能被直接序列化存儲.

例如: 

數據模型:

using UnityEngine;  
using System;  
using System.Collections.Generic;  
  
[Serializable]  
public class Enemy  
{  
    [SerializeField]  
    string name;  
    [SerializeField]  
    List<string> skills;  
  
    public Enemy(string name, List<string> skills)  
    {  
        this.name = name;  
        this.skills = skills;  
    }  
}  

實際使用:

List<Enemy> enemies = new List<Enemy>();  
enemies.Add(new Enemy("怪物1", new List<string>() { "攻擊" }));  
enemies.Add(new Enemy("怪物2", new List<string>() { "攻擊", "恢復" }));  
Debug.Log(JsonUtility.ToJson(enemies));  

輸出為:{}

輸出是沒有任何的json字符串。

------------------------------------------------------------------------------------------------

在unity的官方網站,ISerializationCallbackReceiver繼承的方法被提出,用的時候把此腳本放到項目里.

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

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

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

// Dictionary<TKey, TValue>
[Serializable]
public class Serialization<TKey, TValue> : ISerializationCallbackReceiver
{
    [SerializeField]
    List<TKey> keys;
    [SerializeField]
    List<TValue> values;

    Dictionary<TKey, TValue> target;
    public Dictionary<TKey, TValue> ToDictionary() { return target; }

    public Serialization(Dictionary<TKey, TValue> target)
    {
        this.target = target;
    }

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

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

使用:

// List<T> -> Json ( 例 : List<Enemy> )  
string str = JsonUtility.ToJson(new Serialization<Enemy>(enemies)); // 輸出 : {"target":[{"name":"怪物1,"skills":["攻擊"]},{"name":"怪物2","skills":["攻擊","恢復"]}]}  
// Json-> List<T>  
List<Enemy> enemies = JsonUtility.FromJson<Serialization<Enemy>>(str).ToList();  
  
// Dictionary<TKey,TValue> -> Json( 例 : Dictionary<int, Enemy> )  
string str = JsonUtility.ToJson(new Serialization<int, Enemy>(enemies)); // 輸出 : {"keys":[1000,2000],"values":[{"name":"怪物1","skills":["攻擊"]},{"name":"怪物2","skills":["攻擊","恢復"]}]}  
// Json -> Dictionary<TKey,TValue>  
Dictionary<int, Enemy> enemies = JsonUtility.FromJson<Serialization<int, Enemy>>(str).ToDictionary();  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM