我正在尝试使用Firebase为一个统一项目创建一个高分系统。要检索JSON,我正在使用RESTCLIENT。我已经成功地上传了分数,但是反序列化它们证明是个问题。
JSON = "{"UserName1":{"Name":"UN1","ScoreVal":"99/100"},"UserName2":{"Name":"UN2","ScoreVal":"100/100"}}"
[Serializable]
public class RootObject
{
public Score score { get; set; }
}
[Serializable]
public class Score
{
public string Name;
public string ScoreVal;
public Score(string name, string scoreVal)
{
this.Name = name;
this.ScoreVal = scoreVal;
}
}
理想的解决方案应遵循以下JSON格式:
{
"Level1":{
"User1":{
"Name":"User1",
"Score":"100/100"
},
"User2":{
"Name":"User2",
"Score":"100/100"
}
},
"Level2": {
"User1": {
"Name":"User1",
"ScoreVal":"99/100"
},
"User2": {
"Name":"User2",
"ScoreVal":"100/100"
}
}
}
我尝试从unity,newtonsoft和我自己的jsonhelper中使用JsonUtility:
public static class JsonHelper2
{
public static T[] FromJson<T>(string json)
{
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.Items;
}
public static string ToJson<T>(T[] array)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper);
}
public static string ToJson<T>(T[] array, bool prettyPrint)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper, prettyPrint);
}
[Serializable]
private class Wrapper<T>
{
public T[] Items;
}
}
只有一个条目时我可以检索数据,但是有多个用户名时我无法获得分数。
答案 0 :(得分:1)
您的json具有固定数量的级别和固定数量的用户。您实际上需要这样的对象来反序列化它:
public class Scores
{
public Users Level1 {get;set;}
public Users Level2 {get;set;}
}
public class Users
{
public User User1 {get;set;}
public User User2 {get;set;}
}
public class User
{
public string Name {get;set;}
public string Score {get;set;}
}
假设您的意图不仅是拥有2个固定级别和2个固定用户,您的json的结构应如下所示(请注意,级别是一个数组,级别内的分数是数组):
{
"levels": [{
"name": "Level 1",
"scores": [{
"user": "User1",
"score": "8/10"
}, {
"user": "User2",
"score": "7/10"
}]
},
{
"name": "Level 2",
"scores": [{
"user": "User1",
"score": "9/10"
}, {
"user": "User3",
"score": "6/10"
}]
}
]
}
那么您的C#类将是:
public class Score
{
public string user {get;set;}
public string score {get;set;}
}
public class Level
{
public string name {get;set;}
public IList<Score> scores {get;}
public Level()
{
scores = new List<Score>();
}
}
public class RootObject
{
public IList<Level> levels {get;}
public RootObject()
{
levels = new List<Level>();
}
}
实际上,如果您实际上只是想用2个固定用户的分数来跟踪2个固定级别,则您的json应该与我介绍的初始类结构兼容。