在Unity中解析嵌套的JSON

6

我有一个解析这个json的问题:

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

这是我的代码:

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

    }
}

我收到了这个错误信息:"对象引用未设置为对象的实例"。我已经尝试过成功解析一个非嵌套的JSON,但是现在我不明白为什么即使创建了适当的类也无法工作。

如果您将RootObject定义为动态对象,这是否有助于您找出必要的结构? - TZubiri
2个回答

11

JsonUtility不支持属性。只需删除{get; set;}即可。

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

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

1
非常感谢!一直在寻找这个解决方案!非常好用,再次感谢! - Silvering

4
Unity的JSON实现就像小孩子为他们的CS1项目写的一样。最多只能用于一些不太严肃的JSON用途... ;-)
建议使用:JSON .NET For Unity,如果你花得起的话。
或者... 如果你想坚持使用Unity的JSON实现,请使用https://github.com/Bekwnn/UnityJsonHelper这个库。这个库解决了你描述的确切问题。

这也非常棒而且免费:http://wiki.unity3d.com/index.php?title=JSONObject - turnipinrut

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接