本文介绍了JSON解析C#模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我似乎无法解析一些json来获取模型.
I cannot seem to parse through some json to get it to a model.
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; }
}
我的课:
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);
我遇到的问题是串行器.它无法正确返回模型,导致稍后尝试查看数据时出现空引用异常.我尝试使用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);
*您可以使用属性重命名
*You can rename it with an attribute
这篇关于JSON解析C#模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!