Reputation: 1818
When I try to use JsonUtility to parse the JSON from a REST call returning an array of elements, it fails saying that top level must be an object. C'mon guys. That's ridiculous.
OK, moving on to figuring out how to use Newtonsoft.json because it works well everywhere else.
Tried using JSON .NET for Unity out of the asset store. Seemed like it would work fine and did in the editor, but didn't work (calls to it failed with exceptions) when I tried to use it in a Mac local build on my dev macbook pro. So if it doesn't work on my dev machine and for mac builds, then it's a no go. https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347
Tried using jilleJr's version from here: https://github.com/jilleJr/Newtonsoft.Json-for-Unity but the installation instructions caused the package manager to not be able to open. I get a null reference exception when following the directions to add the package directly into my manifest.json
So what's the secret to making JSON work in Unity 2019/2020 right now? Seems like a huge problem for a platform to have.
Upvotes: 1
Views: 10708
Reputation: 4888
Open *YourUnityProject*/Packages/manifest.json
and add the following line to the dependencies object.
"com.unity.nuget.newtonsoft-json": "2.0.0",
To serialize and deserialize data use these functions:
using Newtonsoft.Json;
public class Data
{
int[] numbers;
}
string json = JsonConvert.SerializeObject(new Data());
Data data = JsonConvert.DeserializeObject<Data>(json);
Upvotes: 5
Reputation: 186
I wouldn't say it's a problem with Unity, back when I was trying to read data in from serialised JSON. JsonUtility
worked a treat when serialising/deserialising to/from a class. I also preferred it to Newtonsoft.json, mainly because it was part of UnityEngine
For example:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class JSONRW : MonoBehaviour
{
PersonData data;
string jsonPath = "Assets/TestJSON.json";
private void Start()
{
//Read in JSON file
string jsonString = File.ReadAllText(jsonPath);
data = JsonUtility.FromJson<PersonData>(jsonString);
Debug.Log(data.client[0].name); //Outputs A
//Write to JSON file
data.client[0].name = "Luc"; //Changes the name of the entry named A
File.WriteAllText(jsonPath, JsonUtility.ToJson(data)); //Writes updata back to file
}
}
[System.Serializable]
public class Person
{
public string name;
public int age;
public Person(string _name, int _age)
{
name = _name;
age = _age;
}
}
[System.Serializable]
public class PersonData
{
public List<Person> client;
}
JSON file:
{
"client": [
{
"name": "A",
"age": 10
},
{
"name": "B",
"age": 20
},
{
"name": "C",
"age": 30
},
{
"name": "D",
"age": 40
}
]
}
Upvotes: 0