将嵌套的json统一在一起

时间:2016-10-20 13:30:06

标签: c# json unity3d

解析这个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但是我不明白为什么但是在创建了适当的类之后仍然无法工作。

2 个答案:

答案 0 :(得分:9)

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

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

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

答案 1 :(得分:2)

Unity的JSON实现很像一个小孩子为他们的CS1项目写的东西。对于任何严肃的JSON使用,它“缺乏”......; - )

建议您使用:JSON .NET For Unity,如果您可以为此付出代价。

或者......如果您希望坚持使用Unity的JSON实现,请使用https://github.com/Bekwnn/UnityJsonHelper。该库解决了您描述的确切问题。