Skip to content

Instantly share code, notes, and snippets.

@Haosvit
Last active July 20, 2021 16:07
Show Gist options
  • Select an option

  • Save Haosvit/fc6e30b331375b44a9b289fba85103c3 to your computer and use it in GitHub Desktop.

Select an option

Save Haosvit/fc6e30b331375b44a9b289fba85103c3 to your computer and use it in GitHub Desktop.
Unity doesn't support parsing an array from json. This JsonHelper will help.
using System;
using UnityEngine;
[Serializable]
public class Building
{
public string ID;
public string Name;
public double Area;
public float Height;
public byte Floor;
public int Room;
public float Longitude;
public float Latitude;
public string Detail;
}
{ "Items" : [
{
"ID":"Cube1",
"Name":"A cube",
"Height":"100",
"Floor":"0",
"Room":"0",
"Longitude":"123",
"Latitude":"321",
"Detail":""
},
{
"ID":"bridge1",
"Name":"Bridge",
"Height":"4",
"Floor":"0",
"Room":"0",
"Longitude":"33",
"Latitude":"2",
"Detail":""
}
]
}
using System;
using UnityEngine;
public static class JsonHelper
{
public static T[] FromJson<T>(string json)
{
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.Items;
}
public static string ToJson<T>(T[] array)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper);
}
public static string ToJson<T>(T[] array, bool prettyPrint)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper, prettyPrint);
}
[Serializable]
private class Wrapper<T>
{
public T[] Items;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment