引用
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
JSON转实体类
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
string jsonStr = "{\"name\": \"Tom\", \"age\": 20, \"gender\": \"male\"}";
Person person = JsonConvert.DeserializeObject<Person>(jsonStr);
JSON转List
方法一
json
{
"data": [
{
"Id":"0",
"Username":"Vreeswijk",
"ProfilePicture":"media/user/0.png"
},
{
"Id":"1",
"Username":"Mony",
"ProfilePicture":"media/user/12.png"
}
]
}
实现
JObject obj = JObject.Parse(json);
//Shou是于json中数组一个元素所对应的类
List<Shou> root = JsonConvert.DeserializeObject<List<Shou>>(obj["data"].ToString());
方法二
json:
{
"user":{
[
{
"Id":"0",
"Username":"Vreeswijk",
"ProfilePicture":"media/user/0.png"
}
]
},
"token":{
[
{
"access_token":"myToken1",
"refresh_token":"myToken2",
"expires_in":3600,
"expires_on":1577363756
}
]
}
}
两个类:
public class Token
{
public string access_token { get; set; }
public string refresh_token { get; set; }
public int expire_in { get; set; }
public int expire_on { get; set; }
//省略了构造方法
}
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string ProfilePicture { get; set; }
//省略了构造方法
}
实现
var jObject = JObject.Parse(json);
var userPropery = jObject["user"] as JArray;
List<User> userList= new List<User>();
foreach (var property in userPropery )
{
var propertyList = JsonConvert.DeserializeObject<List<user>>(property.ToString());
//List集合中的AddRange方法和Add方法的不同之处在于,Add方法为在集合末尾添加单个元素对象,而AddRange方法可以为添加整个目标list集合。
userList.AddRange(propertyList);
}
结合使用
json:
{
"number": 1,
"day": "星期九",
"user":{
[
{
"Id":"0",
"Username":"Vreeswijk",
"ProfilePicture":"media/user/0.png"
}
]
},
"token":{
"access_token":"myToken1",
"refresh_token":"myToken2",
"expires_in":3600,
"expires_on":1577363756
}
}
两个类:文章来源:https://www.toymoban.com/news/detail-721971.html
public class Token
{
public string access_token { get; set; }
public string refresh_token { get; set; }
public int expire_in { get; set; }
public int expire_on { get; set; }
//省略了构造方法
}
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string ProfilePicture { get; set; }
//省略了构造方法
}
public class Data
{
public int number { get; set; }
public string day { get; set; }
public List<User> userList { get; set; }
public Token token { get; set; }
//省略了构造方法
}
实现文章来源地址https://www.toymoban.com/news/detail-721971.html
var jObject = JObject.Parse(json);
List<User> userList = JsonConvert.DeserializeObject<List<Shou>>(jObject["data"].ToString());
Token token = JsonConvert.DeserializeObject<Token>(jObject["token"]);
int number = int.Parse(jObject["number"]);
string day = jObject["day"].ToString();
Data data = new Data(number,day,userList,token);
到了这里,关于C# JSON转为实体类和List,以及结合使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!