6

I have an issue parsing this json :

{
    "product_info":
    {
        "title": "Product Name"
    }
}

here is my code :

using UnityEngine;
using System.Collections;
using System.IO;
using System.Net;
using UnityEngine.UI;

public class ReadJson : MonoBehaviour
{
    public Text myText;

    [System.Serializable]
    public class ProductInfo
    {
        public string title { get; set; }
    }

    [System.Serializable]
    public class RootObject
    {
        public ProductInfo product_info { get; set; }
    }

    void Start () {

        TextAsset asset = Resources.Load (Path.Combine ("Json", "toulouse")) as TextAsset;

        RootObject m = JsonUtility.FromJson<RootObject> (asset.text);

        Debug.Log (m.product_info.title);

    }
}

I receive this error message : "Object reference not set to an instance of an object". I already tried, with success to parse a not nested json but not I don't understand why but doesn't work even after created the appropriated class.

Silvering
  • 756
  • 1
  • 6
  • 33
  • If you define RootObject as a dynamic object, could this help you find out the necessary structure? – TZubiri Oct 20 '16 at 13:39

2 Answers2

11

The JsonUtility does not support properties. Just remove the { get; set;}

[System.Serializable]
public class ProductInfo
{
    public string title;
}

[System.Serializable]
public class RootObject
{
    public ProductInfo product_info;
}
Everts
  • 10,408
  • 2
  • 34
  • 45
4

Unity's JSON implementation is much like what a small child would write for their CS1 project. It's "lacking" at best for any serious JSON usage... ;-)

Recommend using: JSON .NET For Unity if you can pony up for it.

Or... use https://github.com/Bekwnn/UnityJsonHelper if you wish to stick with Unity's JSON implementation. This library solves the exact problem you describe.

boop
  • 7,413
  • 13
  • 50
  • 94
slumtrimpet
  • 3,159
  • 2
  • 31
  • 44