Unity从服务器反序列化

时间:2017-04-05 12:54:32

标签: json unity3d serialization deserialization

我已经尝试了几个小时来从我的服务器反序列化我们的高分系统信息。但是我收到了一个错误:

  

ArgumentException:JSON必须表示对象类型。

这就是我反序列化的方式(scores是Scores类型):

public void Deserialize()
{
    Debug.Log("From Server is ::::: -----> " + FromServer);
    scores = JsonUtility.FromJson<Scores> (FromServer);
}

这是我的服务器生成的Json信息。我究竟做错了什么?

 [
    {
        "ScoreID": "8",
        "GoogleID": "asasda",
        "Score": "258"
    },
    {
        "ScoreID": "11",
        "GoogleID": "kjjahushcjkasjkcajskndas",
        "Score": "258"
    },
    {
        "ScoreID": "10",
        "GoogleID": "aakhskjbjkabsjjkasd",
        "Score": "258"
    },
    {
        "ScoreID": "9",
        "GoogleID": "mnbabksgkajsd",
        "Score": "258"
    },
    {
        "ScoreID": "13",
        "GoogleID": "kajiuskabkjshdkhausd",
        "Score": "258"
    },
    {
        "ScoreID": "7",
        "GoogleID": "asasdas,mgkhgjhbhjaf",
        "Score": "258"
    },
    {
        "ScoreID": "6",
        "GoogleID": "ss",
        "Score": "258"
    },
    {
        "ScoreID": "5",
        "GoogleID": "kljkuasjkba",
        "Score": "258"
    },
    {
        "ScoreID": "4",
        "GoogleID": "asdadasdasdasdw",
        "Score": "258"
    },
    {
        "ScoreID": "3",
        "GoogleID": "asdadsasd",
        "Score": "258"
    },
    {
        "ScoreID": "2",
        "GoogleID": "kbaskjkjsbnkjas",
        "Score": "258"
    },
    {
        "ScoreID": "12",
        "GoogleID": "lahaushyuiahkjsjksd",
        "Score": "258"
    },
    {
        "ScoreID": "1",
        "GoogleID": "254asdasd54a5s1das2d1as54d",
        "Score": "259"
    },
    {
        "ScoreID": "14",
        "GoogleID": "kjaskjhjkahsjkdnjkasd",
        "Score": "6859"
    }
]

这些是我尝试序列化的类:

[System.Serializable]
public class LeaderBoardEntries
{
    public int ScoreID;
    public string GoogleID;
    public int Score;
}
[System.Serializable]
public class Scores
{
    public List<LeaderBoardEntries> scores;
}

1 个答案:

答案 0 :(得分:6)

.json文件中只能有一个对象能够通过JsonUtility对其进行反序列化。你的.json不是一个对象,它是一个对象数组。应采用以下格式:

{
    scores: [
    {
        "ScoreID": "8",
        "GoogleID": "asasda",
        "Score": "258"
    },
    {
        "ScoreID": "11",
        "GoogleID": "kjjahushcjkasjkcajskndas",
        "Score": "258"
    }
    ]
}

这个.json字符串可以反序列化为Scores对象。

我同意Unity应该让他们的文档更加清晰。他们需要强调的是,您可以反序列化仅代表1个对象的.json文件。