Alpha Alpha - 4 months ago 14
JSON Question

Parse JSON without plugins

So i have some Json:

{
"name": "Shadow Realm",
"description": "A spooky Haloween inspired map",
"map": {
"version": 79,
"color_palette": [
{
"r": 96,
"g": 209,
"b": 234,
"a": 255
},
{
"r": 255,
"g": 55,
"b": 55,
"a": 255
}]
}
}


And i am am able to read the first few values however i am not able to read the version and i am not sure what i should be reading the map entry as, any ideas?
I would prefer not to have to use a plugin as i wish to keep the project as small as possible if its do-able.

using UnityEngine;
using System.Collections;
using System.Reflection;
using System.Linq;
using System;

[System.Serializable]
public class Tests : MonoBehaviour
{
private string jsonMapData;

void Start()
{
jsonMapData = Import_bnl_bin.LoadResourceTextfile("map.json");
MyClass jsonMap = new MyClass();
jsonMap = JsonUtility.FromJson<MyClass>(jsonMapData);

Debug.Log("Name " + jsonMap.name + " : Desc " + jsonMap.description + " : Version " + jsonMap.version);
}

public class MyClass
{
public string name;
public string description;

public int version;
}
}

Answer

it seems that the classes needed to be serializable

[Serializable]
public class Map
{
    public int version;
    public List<ColorPalette> color_palette;
}

otherwise it fails to read the data, also i ended up removing the

{ get; set; } 

as it was overriding the

.FromJson()

funtion and causing it to return null

Comments