-2

Still on this issue, and I know this is an old post, but I'm also struggling to get C# to parse JSON.

I'm using Unity 2018.2.8f1, and VS 2019 (I also tried on VS 2017).

Here is my Json file (a really really simple one):

{
  "glossary": {
    "title": "example glossary"
  }
}

And this is my C#:

using System;
using System.IO;
using UnityEngine;

[Serializable]
public class GlossaryRoot
{
    public Glossary Glossary { get; set; }
}


[Serializable]
public class Glossary
{
    public string title { get; set; }
}


public class Data_Manager : MonoBehaviour
{
    private void Start()
    {
    
        string filePath = Path.Combine(Application.streamingAssetsPath, "Example.json");
        string dataAsJSON = File.ReadAllText(filePath);

        var myData = JsonUtility.FromJson<GlossaryRoot>(dataAsJSON);

        string myTitle = myData.Glossary.title;

        Debug.Log(myTitle);
    }
}

I'm getting the error: "NullReferenceException: Object reference not set to an instance of an object"

Any ideas on how to solve this issue? I've been looking for solutions, and tried a lot of things, but still with no success.

I know there are multiple issues similar to this one such as: C#, Unity3D, JSON Parsing: Failing to parse JSON into C# object

But still I can't get it to work. Even if I get delete the "gets and sets", I get "Null" in the console.

Any help is appreciated.

Thank you!

FDinis
  • 1
  • 1

1 Answers1

1
  1. You names don't match it should be public Glossary glossary instead.

  2. afaik Unity's Serializer (and therefore also the builtin JsonUtility) doesn't support (de)serialization of properties, rather use fields

so this should work

    [Serializable]
    public class GlossaryRoot
    {
        public Glossary glossary;
    }


    [Serializable]
    public class Glossary
    {
        public string title;
    }
derHugo
  • 83,094
  • 9
  • 75
  • 115