Unity jsonUtility序列化List,Dictionary等泛型

原文地址 https://blog.csdn.net/Truck_Truck/article/details/78292390

// 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]);
        }
    }
}

在这个思路的基础上封装了两个方法出来更方便使用

public class SerializeTools
{
    public static string ListToJson(List l) 
    {
        return JsonUtility.ToJson(new Serialization(l));
    }

    public static List ListFromJson(string str) 
    {
        return JsonUtility.FromJson>(str).ToList();
    }

    public static string DicToJson(Dictionary dic)
    {
        return JsonUtility.ToJson(new Serialization(dic));
    }

    public static Dictionary DicFromJson(string str)
    {
        return JsonUtility.FromJson>(str).ToDictionary();
    }

}

你可能感兴趣的:(Unity)