JSON 正在解析 C# 模型

JSON Parsing C# model

我似乎无法解析一些 json 以将其转化为模型。

JSON:

{
    "status":"ok",
    "count":100,
    "data":[
        {"nickname":"God","id":null,"account_id":1000076613},
        {"nickname":"god0","id":null,"account_id":1005460397},
        {"nickname":"god1father","id":null,"account_id":1002495621},
        {"nickname":"God1Hand","id":null,"account_id":1003183995}]
}

我的模特:

public class UserModel
{
    public List<User> Users;
}

public class User
{

    public int AccountId { get; set; }

    public string Nickname { get; set; }

    public string Id { get; set; }

}

我的Class:

var client = new HttpClient();
var task = await client.GetAsync(APIWebAddress);
var jsonstring = await task.Content.ReadAsStringAsync();
if (jsonstring == null) return null;
var serializer = new JavaScriptSerializer();
UserModel model = serializer.Deserialize<UserModel>(jsonstring);

我遇到的问题是序列化程序。它没有 return 正确地导致我稍后在尝试查看数据时获得空引用异常。我尝试使用 JavaScriptSerializer 和 Json.Net 反序列化器。

试试这个

型号(用json2csharp生成)

public class User
{
    public string nickname { get; set; }
    public object id { get; set; }
    public int account_id { get; set; } // you cant change the name*
}

public class Users
{
    public string status { get; set; } // you cant skip this
    public int count { get; set; } // you cant skip this
    public List<User> data { get; set; }
}

序列化器

这里我们使用Json.NET

Users users =  JsonConvert.DeserializeObject<Users>(json);

DEMO on DotnetFiddle

*可以用属性重命名

您的代码中的问题在于:

UserModel model = serializer.Deserialize<UserModel>(jsonstring);

更改如下:

UserModel model = serializer.Deserialize<UserModel>(jsonstring.Result.ToString());

希望对您有所帮助