【发布时间】:2016-05-05 20:20:47
【问题描述】:
我在将 json 字符串转换为 c# 列表时遇到了一些问题!
这是我从服务器获取的 JSON。
[
{"roundid":1,"coins":700,"created":"2016-03-16 11:13:26","duration":198,"score":765230},
{"roundid":3,"coins":330,"created":"2016-03-16 11:13:56","duration":123,"score":425726},
{"roundid":4,"coins":657,"created":"2016-03-16 11:21:23","duration":432,"score":75384},
{"roundid":8,"coins":980,"created":"2016-03-16 11:23:19","duration":271,"score":827200}
]
在我的 C# 程序中,我尝试使用此函数将我的 json 字符串转换为可用的对象
public List<Round> getPlayerRounds(string username)
{
string url = BaseURL + "op=findUserRounds&username=" + username;
var json = new WebClient().DownloadString(url);
RoundDataList rounds = JsonUtility.FromJson<RoundDataList>(json);
List<Round> playerRounds = new List<Round>();
//for (var i = 0; i < rounds.roundList.Count; i++)
for (var i = 0; i < rounds.roundList.Length; i++)
{
RoundData rd = rounds.roundList[i];
Round r = rd.getRound();
playerRounds.Add(r);
}
return playerRounds;
}
这里出错了
ArgumentException:JSON 必须表示对象类型。
我环顾四周,没有发现任何可行的方法,尝试了 2-3 解决方案,甚至尝试编辑了创建 JSON 字符串的我的 php web 服务。
我的课程是这样的
/* This is previus atempt to solve the issue
[Serializable]
public class RoundDataList
{
public List<RoundData> roundList;
}
*/
[Serializable]
public class RoundDataList
{
public RoundData[] roundList;
}
[Serializable]
public class RoundData
{
public int roundid;
public int coins;
public DateTime created;
public int duration;
public int score;
public Round getRound()
{
Round r = new Round();
r.Roundid = roundid;
r.Coins = coins;
r.Created = created;
r.Duration = duration;
r.Score = score;
return r;
}
}
感谢您观看这篇长文!
【问题讨论】: