首页 > 解决方案 > 统一反序列化

问题描述

我希望在 Unity 中反序列化它并取得了一些成功,但似乎被困在双数组上。这是一些 JSON(仅显示相关内容)

{
"cities": [{
    "name": "London",
    "monuments": [{
            "levels": 15,
            "objBeingIntroduced": "none"
        },
        {
            "levels": 25,
            "objBeingIntroduced": "df"
        }
    ]
}],
"puzzles": [{
    "puzzleId": 1,
    "moves": [
        [{
                "x": 3,
                "y": 3,
                "xInc": 1,
                "yInc": 0
            },
            {
                "x": 5,
                "y": 3,
                "xInc": -1,
                "yInc": 0
            }
        ],
        [{
                "x": 4,
                "y": 3,
                "xInc": 0,
                "yInc": 1
            },
            {
                "x": 4,
                "y": 5,
                "xInc": 0,
                "yInc": -1
            }
        ]
    ],
    "squares": [{
            "x": 3,
            "y": 3,
            "type": "d"
        },
        {
            "x": 5,
            "y": 3,
            "type": "d"
        },
        {
            "x": 4,
            "y": 5,
            "type": "d"
        }
    ]
}]

}

您将如何在 Unity 中用 JSON 反序列化它?

我可以抓住除了移动类别之外的所有细节的拼图部分,因为它是一个双数组。这是我到目前为止所拥有的

[System.Serializable]
public class LevelStructure
{
    public int puzzleId;
    public List<Moves> moves = new List<Moves>();
    public Squares[] squares;
}

[System.Serializable]
public class Levels
{
    public LevelStructure[] result;
}

[System.Serializable]
public class Squares
{
    public int x;
    public int y;
    public string type;
}

[System.Serializable]
public class Moves
{
    public Move[] moves;
}

[System.Serializable]
public class Move
{
    public int x;
    public int y;
    public int xInc;
    public int yInc;
}

我似乎无法弄清楚如何做像“纪念碑”和“移动”部分的双数组。任何关于从这里去哪里的建议都将不胜感激。

既然我相信这种结构很好,那么我如何将 json 实际加载到这些类中呢?

谢谢

标签: arraysjsonunity3d

解决方案


尽管如此,您应该真正考虑您的结构并创建自己的代码,以下是json2csharp.com可以为您做的:

public class Monument
{
    public int levels { get; set; }
    public string objBeingIntroduced { get; set; }
}

public class City
{
    public string name { get; set; }
    public List<Monument> monuments { get; set; }
}

public class Square
{
    public int x { get; set; }
    public int y { get; set; }
    public string type { get; set; }
}

public class Puzzle
{
    public int puzzleId { get; set; }
    public List<List<>> moves { get; set; }
    public List<Square> squares { get; set; }
}

public class RootObject
{
    public List<City> cities { get; set; }
    public List<Puzzle> puzzles { get; set; }
}

推荐阅读