【问题标题】:Parse nested json in unity [duplicate]统一解析嵌套的json [重复]
【发布时间】:2023-04-02 23:13:01
【问题描述】:

我在解析这个 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定义为一个动态对象,这能帮助你找出必要的结构吗?

标签: c# json unity3d


【解决方案1】:

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

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

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

【讨论】:

  • 非常感谢!有一天正在寻找这个解决方案!再次感谢!
【解决方案2】:

Unity 的 JSON 实现非常类似于小孩子为他们的 CS1 项目编写的内容。对于任何严重的 JSON 使用,它充其量是“缺乏”... ;-)

如果你愿意的话,推荐使用:JSON .NET For Unity

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 2021-07-14
  • 2019-03-22
  • 2016-02-19
  • 2017-01-04
  • 1970-01-01
相关资源
最近更新 更多