Search code examples
jsonunity-game-enginejson.net

How do we parse JSON in Unity3d?


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.


Solution

  • 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);