Mån*_*röm 5 c# json unity-game-engine
将json字符串转换为ac#List时遇到一些问题!
这是我从服务器端获得的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}
]
Run Code Online (Sandbox Code Playgroud)
在我的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;
}
Run Code Online (Sandbox Code Playgroud)
我在这里得到错误
ArgumentException:JSON必须表示对象类型.
我环顾四周,没有找到任何有用的东西,试过2-3解决方案甚至尝试编辑我的php webservice创建JSON字符串.
我的类看起来像这样
/* 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;
}
}
Run Code Online (Sandbox Code Playgroud)
感谢您查看这篇长篇文章!
创建一个班级和另一个持有它的班级列表对我有用。
[Serializable]
public class Questions
{
public string id;
public string question;
public string answer1;
public string answer2;
}
[Serializable]
public class QuestionList
{
public List<Questions> list;
}
//and
var jstring = "{\"list\":[{\"id\":\"1\",\"question\":\"lorem Ipsome \",\"answer1\":\"yes\",\"answer2\":\"no\"},{\"id\":\"2\",\"question\":\"lorem Ipsome Sit dore iman\",\"answer1\":\"si\",\"answer2\":\"ne\"}]}";
var result = JsonUtility.FromJson<QuestionList>(jstring);
Run Code Online (Sandbox Code Playgroud)
从列表中,转换为 JSON
List<Questions> questionlist = new List<Questions>();
questionlist.Add(new Questions()
{
answer1 = "yes",
answer2 = "no",
id = "1",
question = "lorem Ipsome "
});
questionlist.Add(new Questions()
{
answer1 = "si",
answer2 = "ne",
id = "2",
question = "lorem Ipsome Sit dore iman"
});
var ql = new QuestionList();
ql.list = questionlist;
var result = JsonUtility.ToJson(ql);
//this gives
{"list":[{"id":"1","question":"lorem Ipsome ","answer1":"yes","answer2":"no"},{"id":"2","question":"lorem Ipsome Sit dore iman","answer1":"si","answer2":"ne"}]}
Run Code Online (Sandbox Code Playgroud)
注意:“list”和 questionList.list 应该同名。
| 归档时间: |
|
| 查看次数: |
21228 次 |
| 最近记录: |