- Home /
How to read an int array using LitJson?
So i'm trying to generate level geometry simply by using Line Renderer and Edge Collider 2D. The level data is stored inside json file and looks like this:
[
{
"id": 0,
"title": "Some level",
"spawnPoint": [0, 5],
"finishPoint": 30,
"xPoses": [0, 10, 20, 30],
"yPoses": [0, 5, 10, 15]
}
]
There is nothing wrong with reading single variables until it comes to arrays. I can't figure out how is it done in LitJson. In my project I have the Level class which looks like this:
public class Level {
public int id { get; set; }
public string title { get; set; }
public int[] spawnPoint { get; set; }
public int[] finishPoint { get; set; }
public float[] xPoses { get; set; }
public float[] yPoses { get; set; }
}
Levels are stored inside the List object and I load them like this
levelData = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/StreamingAssets/Levels/levels.json"));
private List<Level> levelDatabase = new List<Level>();
So the main question is how to read a JSON array (spawnpoint, x/y Poses) and make it into the C# one. Thank you.
Answer by andrey-koms-ua · Dec 16, 2017 at 10:47 PM
For those who stuck with a same problem, I found this workaround:
using System;
public static class JsonHelper {
public static T[] FromJson<T>(string json) {
Wrapper<T> wrapper = UnityEngine.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 UnityEngine.JsonUtility.ToJson(wrapper, true);
}
[SerializableAttribute]
private class Wrapper<T> {
public T[] Items;
}
}
And then it's loaded like this:
List<Level> levels = JsonHelper.FromJson<Level>(jsonString).ToList();
Your answer
Follow this Question
Related Questions
How can i get all of my users data on FireBase using Unity and RestClient json 1 Answer
Load json into array class 1 Answer
How to get a JSON string of a folder structure with c# in Unity3d 2 Answers
Help me with this json code please 1 Answer
How do I print each element of a string array separately to a UI text box 2 Answers