unity嵌套字典转json
时间: 2023-07-19 07:22:33 浏览: 143
iOS数组和字典转JSON格式
在Unity中,我们可以使用JsonUtility类将C#对象序列化为JSON格式的字符串。而对于嵌套字典,我们可以先将其转化为嵌套类对象,再使用JsonUtility类进行序列化。下面是一个示例代码:
```csharp
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
// 嵌套字典
Dictionary<string, Dictionary<string, string>> nestedDict = new Dictionary<string, Dictionary<string, string>>();
nestedDict.Add("dict1", new Dictionary<string, string>());
nestedDict["dict1"].Add("key1", "value1");
nestedDict["dict1"].Add("key2", "value2");
nestedDict.Add("dict2", new Dictionary<string, string>());
nestedDict["dict2"].Add("key3", "value3");
nestedDict["dict2"].Add("key4", "value4");
// 将嵌套字典转化为嵌套类对象
List<NestedClass> nestedList = new List<NestedClass>();
foreach (var item in nestedDict)
{
Dictionary<string, string> dict = item.Value;
List<NestedClass.InnerClass> innerList = new List<NestedClass.InnerClass>();
foreach (var innerItem in dict)
{
NestedClass.InnerClass innerClass = new NestedClass.InnerClass
{
Key = innerItem.Key,
Value = innerItem.Value
};
innerList.Add(innerClass);
}
NestedClass nestedClass = new NestedClass
{
DictName = item.Key,
DictList = innerList
};
nestedList.Add(nestedClass);
}
// 序列化嵌套类对象为JSON格式的字符串
string jsonString = JsonUtility.ToJson(nestedList, true);
Debug.Log(jsonString);
}
// 嵌套类对象
[System.Serializable]
public class NestedClass
{
public string DictName;
public List<InnerClass> DictList;
[System.Serializable]
public class InnerClass
{
public string Key;
public string Value;
}
}
}
```
这段代码将嵌套字典转化为了嵌套类对象,然后使用JsonUtility类将嵌套类对象序列化为JSON格式的字符串,并在控制台输出该字符串。需要注意的是,使用JsonUtility类进行序列化时,被序列化的类必须是public修饰的。
阅读全文