首页 > 解决方案 > Unity:将 json 字符串反序列化为 C# 对象

问题描述

我正在尝试将 json 文件读入我的 C# 代码。json 文件包含以下字符串:

{
    "allLevels": [{
        "level": 1,
        "name": "XXX",
        "type": "XXX",
        "description": "XXX",
        "input": "XXX",
        "key": "XXX",
        "keyType": "XXX",
        "output": "XXX"
    },
    {
        "level": 2,
        "name": "XXX",
        "type": "XXX",
        "description": "XXX",
        "input": "XXX",
        "key": "XXX",
        "keyType": "XXX",
        "output": "XXX"
    }],
    "funFacts": [
        "XXX",
        "XXXXX"     
        ]
}

我有两个类,分别AllLevel.cs如下ContentJson.cs所示:

[System.Serializable]
public class AllLevel
{
    public int level { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public string description { get; set; }
    public string input { get; set; }
    public object key { get; set; }
    public string keyType { get; set; }
    public string output { get; set; }
}

using System.Collections.Generic;
[System.Serializable]
public class ContentJson
{
    public IList<AllLevel> allLevels { get; set; }
    public IList<string> funFacts { get; set; }
}

我能够读取 .json 文件,但无法将其分配给ContentJson对象。下面代码片段中的调试日志只打印字符串“ContentJson”,并且任何访问对象内部内容的尝试都会给出 NullReferenceException。为什么 FromJson 无法反序列化对象。

public static void populateGamedata(string gameDataFileName)
{
    if (gameDataFileName == null)
        return;
    // Path.Combine combines strings into a file path
    // Application.StreamingAssets points to Assets/StreamingAssets in the Editor, and the StreamingAssets folder in a build        
    string filePath = Path.Combine(Application.streamingAssetsPath, gameDataFileName);
    if (File.Exists(filePath))
    {
        // Read the json from the file into a string
        string dataAsJson = File.ReadAllText(filePath);
        // Pass the json to JsonUtility, and tell it to create a ContentJson object from it
        ContentJson gameData = JsonUtility.FromJson<ContentJson>(dataAsJson);

        // Retrieve the levels and funfacts property of gameData
        levels = gameData.allLevels;
        funFacts = gameData.funFacts;
        Debug.Log("dataAsJson === " + dataAsJson);
        Debug.Log("gameData == " + gameData.ToString());
        Debug.Log("levels == " + levels[0].name);            
    }
    else
    {
        Debug.LogError("Cannot load game data!");
    }
}

在此处输入图像描述 PS:我手动创建了 json 文件。

标签: c#jsonunity3dfromjson

解决方案


推荐阅读