JsonUtility解析字典

这篇博客介绍了如何在Unity中使用JsonUtility解析字典类型的数据。通过让字典类型实现ISerializationCallbackReceiver接口,将键值对列表分开解析,以达到解析目的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

介绍

使用Unity自身的JsonUtility解析字典

  • 字典类型实现接口ISerializationCallbackReceiver,相当于在转换之间进行键值对列表的分开解析
Json
{
    "KeyList": [1, 2],
    "ValueList": [{
        "panelTypeString": "1",
        "path": "q"
    }, {
        "panelTypeString": "2",
        "path": "w"
    }]
}
代码
using System;
using System.Collections.Generic;
using UnityEngine;

public class JsonLoad : MonoBehaviour
{
    void Start()
    {
        LoadJson();
    }

    private void LoadJson()
    {
        string str = Resources.Load<TextAsset>("Json").text;
        UIDataJson json = JsonUtility.FromJson<UIDataJson>(str);
        Dictionary<int, UIData> dic = json.infodic;
        foreach (var item in dic)
        {
            Debug.LogError(item.Key + ":" + item.Value);
        }
    }
}

[Serializable]
public class UIDataJson:ISerializationCallbackReceiver
{
    public Dictionary<int, UIData> infodic;
    public UIDataJson(Dictionary<int,UIData> data)
    {
        this.infodic = data;
    }

    //键值对解析
    public List<int> KeyList = new List<int>();
    public List<UIData> ValueList = new List<UIData>();
    public void OnAfterDeserialize()
    {
        infodic = new Dictionary<int, UIData>();
        for (int i = 0; i < Math.Min(KeyList.Count,ValueList.Count); i++)
        {
            infodic.Add(KeyList[i], ValueList[i]);
        }
    }

    public void OnBeforeSerialize()
    {
        KeyList.Clear();
        ValueList.Clear();
        foreach (var item in infodic)
        {
            KeyList.Add(item.Key);
            ValueList.Add(item.Value);
        }
    }
}

[Serializable]
public class UIData
{
    public string panelTypeString;
    public string path;
    public UIData(string type, string path)
    {
        this.panelTypeString = type;
        this.path = path;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值