【问题标题】:C# Unity Reading data from JSON into an Object ArrayC# Unity 将数据从 JSON 读取到对象数组中
【发布时间】:2020-10-02 14:32:11
【问题描述】:

我正在尝试从 JSON 文件中读取一系列项目到 Object 数组中。 不幸的是,它返回为 null。

很像这个问题Unity C# JsonUtility is not serializing a list

所以在我的特殊情况下,我有该项目的类:

[Serializable]
public class StateData
{
    public string name;
    public string location;
    public string gameText;
}

项目集合的类:

[Serializable]
public class StateDataCollection
{
    public List<StateData> stateDatas = new List<StateData>();
}

以及调用它的类:

public class JSONReader : MonoBehaviour
{
    private const string Path = @"S:\repos\myProject\Assets\gameText\";

    void Start()
    {
        string json = File.ReadAllText(Path + "StateData.json");
        StateDataCollection stateDataCollection = new StateDataCollection();
        stateDataCollection = JsonUtility.FromJson<StateDataCollection>(json);
    }
}

终于有了json

{
"StateData":[
{
"name": "name", 
"location":"location",
"gameText" : "gameText"},
{
"name": "name", 
"location":"location",
"gameText" : "gameText"},
{
"name": "name", 
"location":"location",
"gameText" : "gameText"
}]
}

对象返回为空。 文件读取正常。

有什么想法是失败的吗? 泰!

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    我会先检查几件事:

    • 检查文件是否确实存在。只需使用一个小的Debug.Log(File.Exists(path))
    • 尝试其他路径 -> 保存类似:Application.persistentDataPath。在 Windows 上,这将为您提供如下内容:%userprofile%\AppData\Local\Packages\LocalState。这可确保您能够读取/写入文件。
    • 用实际数据填写List,以便区分保存的列表和默认列表。

    编辑 1:
    我刚刚复制了您的代码并对其进行了一些调整。它并不完美,但它肯定对我有用。

    状态数据:

    using System;
    
    [Serializable]
    public struct StateData
    {
        public string m_Name;
        public string m_Location;
        public string m_GameText;
    
        public StateData(string name, string location, string gameText)
        {
            m_Name = name;
            m_Location = location;
            m_GameText = gameText;
        }
    }
    

    StateDataCollection:

    using System;
    using System.Collections.Generic;
    
    [Serializable]
    public class StateDataCollection
    {
        public List<StateData> m_StateData;
    
        public StateDataCollection() => m_StateData = new List<StateData>();
    }
    

    JSONReader:

    using System.IO;
    using UnityEngine;
    
    public class JSONReader : MonoBehaviour
    {
        private const string FILENAME = "StateData.json";
    
        private string m_path;
        public string FilePath {
            get => m_path;
            set => m_path = value;
        }
    
        void Start()
        {
            FilePath = Path.Combine(Application.persistentDataPath, FILENAME);
            Debug.Log(FilePath);// delete me
    
            StateDataCollection stateDataCollection = new StateDataCollection();
            stateDataCollection.m_StateData.Add(new StateData("Peter", "X", "123"));
            stateDataCollection.m_StateData.Add(new StateData("Annie", "Y", "42"));
            stateDataCollection.m_StateData.Add(new StateData("TheGuyFromTheSupermarket", "Supermarket", "666"));
    
    
            SaveStateDataCollectionToPath(FilePath, stateDataCollection);
    
            LoadStateDataCollectionFromPath(FilePath);
        }
    
        private void SaveStateDataCollectionToPath(string path, StateDataCollection stateDataCollection)
        {
            // ToDo: some checks on path and stateDataCollection
            string json = JsonUtility.ToJson(stateDataCollection, true);// prettyPrint active
    
            File.WriteAllText(path, json);
        }
    
        private void LoadStateDataCollectionFromPath(string path)
        {
            if(File.Exists(path)) {
                Debug.Log($"File exists at: {path}");// delete me
    
                string json = File.ReadAllText(path);
                StateDataCollection stateDataCollection = JsonUtility.FromJson<StateDataCollection>(json);
    
                // delete me
                Debug.Log($"StateDataCollection count: { stateDataCollection.m_StateData.Count}");
                int i = 1;
                stateDataCollection.m_StateData.ForEach(o => {
                    Debug.Log(
                        $"Item Nr.: {i}\n" +
                        $"Name: {o.m_Name}\n" +
                        $"Location: {o.m_Location}\n" +
                        $"GameText: {o.m_GameText}\n\n");
                    ++i;
                });
            }
        }
    }
    

    我还添加了几个Debug.Log()s 用于测试。
    用法:
    SaveStateDataCollectionToPath(FilePath, stateDataCollection); 活动的情况下运行一次,在没有它的情况下运行一次。 控制台应显示 3 个项目。
    编辑 2:
    我认为您的问题可能是违反命名约定。 File 需要using System.IO;,在File 旁边还包含Path。不幸的是,您还将const string 命名为“路径”。

    【讨论】:

    • 嘿ge.go,非常感谢您的回复。你帮我找出了什么问题。我使用输出文件作为构建 JSON 文本的基础,然后它就起作用了。显然格式有问题,但其余部分我保持不变。所有的逗号、括号、括号等都已到位。只有缩进不同,这似乎不是错误的原因,但它有效。 TY 的帮助!
    猜你喜欢
    • 2012-11-22
    • 1970-01-01
    • 2012-07-13
    • 2023-03-31
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多