Reputation: 1
I am trying to load a json file to unity, everything works fine until i try to load a 2D array. My json file is in this form:
"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 ]
]
I am currently using JsonHelper as a wrapper
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;
}
}
Upvotes: 0
Views: 777
Reputation: 179
Try using Newtonsoft.Json. I find it the best to work with. Here's an example:
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;
}
}
The result written to the console:
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,
Upvotes: 0
Reputation: 134
Did you check if your string is in valid json format?
Strings in json format are surrounded by "{ }".
Good way to check is to throw it in online json parser like http://json2csharp.com/
Upvotes: 1