我正在尝试将json文件加载为统一,一切正常,直到我尝试加载2D数组。 我的json文件格式如下:
"name": "Group 1",
"ID": 0,
"Components": 8,
"RelationArray": [
[ 0, 1, 0, 0, 0, 0, 0, 0 ],
[ 1, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 1, 0, 0, 0, 0 ],
[ 0, 0, 1, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 1, 0, 0 ],
[ 0, 0, 0, 0, 1, 0, 1, 1 ],
[ 0, 0, 0, 0, 0, 1, 0, 1 ],
[ 0, 0, 0, 0, 0, 0, 1, 0 ]
]
我目前正在使用JsonHelper作为包装器
public class JsonHelper
{
public static T[] FromJson<T>(string json)
{
Wrapper<T> wrapper = UnityEngine.JsonUtility.FromJson<Wrapper<T>>(json);
Debug.Log(wrapper.Objects);
return wrapper.Objects;
}
public static string ToJson<T>(T[] array)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Objects = array;
return UnityEngine.JsonUtility.ToJson(wrapper);
}
[Serializable]
private class Wrapper<T>
{
public T[] Objects;
}
}
答案 0 :(得分:1)
答案 1 :(得分:0)
尝试使用Newtonsoft.Json。我发现最好与之合作。这是一个示例:
using System;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
// this is just a string escaped version of your json that you linked.
// You should have something like this in code by the time you want to deserialize it.
var jsonString = "{\r\n\t\"name\": \"Group 1\",\r\n\t\"ID\": 0,\r\n\t\"Components\": 8,\r\n\t\"RelationArray\": [\r\n\t\t[0, 1, 0, 0, 0, 0, 0, 0],\r\n\t\t[1, 0, 0, 0, 0, 0, 0, 0],\r\n\t\t[0, 0, 0, 1, 0, 0, 0, 0],\r\n\t\t[0, 0, 1, 0, 0, 0, 0, 0],\r\n\t\t[0, 0, 0, 0, 0, 1, 0, 0],\r\n\t\t[0, 0, 0, 0, 1, 0, 1, 1],\r\n\t\t[0, 0, 0, 0, 0, 1, 0, 1],\r\n\t\t[0, 0, 0, 0, 0, 0, 1, 0]\r\n\t]\r\n}";
var obj = JsonConvert.DeserializeObject<YourObject>(jsonString);
Console.WriteLine(obj.name);
Console.WriteLine(obj.ID);
Console.WriteLine(obj.Components);
for(int i = 0; i < obj.RelationArray.Length; i++){
for(int j = 0; j < obj.RelationArray[i].Length; j++){
Console.Write(obj.RelationArray[i][j] + ", ");
}
Console.WriteLine();
}
}
// make a class to deserialize your json string into
class YourObject {
public String name;
public int ID;
public int Components;
public int[][] RelationArray;
}
}
将结果写入控制台:
Group 1
0
8
0, 1, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 1, 0, 1, 1,
0, 0, 0, 0, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 1, 0,