C#Json DeserializeObject数组

时间:2019-02-20 16:17:39

标签: c#

我正在尝试进行一些登录操作,但我一直陷于困境。我整天都在努力。我只想这样做,所以当将密钥放入文本框中时,它将检查密钥并返回用户名。我已经为此制作了一个JSON文件。

public static string getUser(string key)
{
    try
    {
        WebClient client = new WebClient { Proxy = null };
        string link = client.DownloadString("https://snyicalistic123.000webhostapp.com/aqua.json");
        dynamic jsa = JsonConvert.DeserializeObject<userGroup>(link);
        string username = jsa.user1[link.IndexOf(key)].username;
        return username;
    }
    catch(Exception e)
    {
        return $"Failed... {e.Message}";
    }
}

public class user
{
    public string username { get; set; }
    public bool isBanned { get; set; }
}

public class userGroup
{
    public user user1;
}

2 个答案:

答案 0 :(得分:1)

您的json格式错误

您应该有一个像这样的json

[
{
    "username": "Preazy_RBLX",
    "isBanned": false
}, {
    "username": "inazmul123",
    "isBanned": false
}, {
    "username": "Slormracer7",
    "isBanned": false
}
]

那么您应该能够将DeserializeObject变成这样的东西

dynamic jsa = JsonConvert.DeserializeObject<List<user>>(link);

答案 1 :(得分:0)

问题与您拥有的json的结构有关。

但是,如果不受您的控制,则可以将其反序列化为
string-user对字典来解决问题:

try
{
    WebClient client = new WebClient { Proxy = null };
    string link = client.DownloadString("https://snyicalistic123.000webhostapp.com/aqua.json");
    Dictionary<string, user> jsa = JsonConvert.DeserializeObject<Dictionary<string, user>>(link);
    string username = jsa[key].username;
    return username;
}
catch(Exception e)
{
    return e.Message;
}

Here是测试代码的dotnet提琴。