C# JsonSerializationException 无法反序列化当前 JSON 对象

莱斯库伊

我对 json 有疑问(我以前从未接触过 json)。我的代码基本上是复制粘贴这个Read and parse a Json File in C#

using (StreamReader r = new StreamReader(RandomUtils.launcherPath() + @"\users.json"))
{
    string json = r.ReadToEnd();
    List<Account> items = JsonConvert.DeserializeObject<List<Account>>(json);
} 

public class Account
{
    public string users;
    public string username;
    public string type;
    public string uuid;
    public string sessionToken;
    public string accessToken;
}

和我的json(阻止用户)

{
  "users": {
    "[email protected]": {
      "username": "[email protected]", //Just bug here ill fix later
      "type": "mojang",
      "uuid": "008d8151613d4ef4bf491520f90930c1",
      "sessionToken": "token",
      "accessToken": "Anothertoken"
    }
  }
}
哔叽

我在你的 json 中看不到任何列表,你必须修复类

 data = JsonConvert.DeserializeObject<Data>(json);

班级

  public class Data
{
    public Dictionary<string,Account> users { get; set; }
}

public class Account
{
    public string username { get; set; }
    public string type { get; set; }
    public string uuid { get; set; }
    public string sessionToken { get; set; }
    public string accessToken { get; set; }
}

但如果你喜欢一个列表,你可以使用这个代码

    List<Account> listUsers = ((JObject)JObject.Parse(json)["users"]).Properties()
                                             .Select(x => x.Value.ToObject<Account>())
                                             .ToList();

或者如果您只有一个用户

Account account = ((JObject)JObject.Parse(json)["users"]).Properties()
                                 .Select(x => x.Value.ToObject<Account>())
                                 .First();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章