[英]Get JSON data and convert it into a class in c#
Hi i would like to convert some json data into an instance of ac# class : 嗨,我想将一些json数据转换为ac#类的实例:
for example if i have this json code : 例如,如果我有此json代码:
"product": [
{
"CarBrand": [
"HippoCars",
"CondorTrucks",
"CheetahMotors"
],
"CarCategory": [
"truck",
"car",
"MotorBike"
And the class : 和类:
public class Catalogue
{
public List<Product> product { get; set; }
public List<string> CarBrand { get; set; }
public List<string> CarCategory { get; set; }
}
How can I convert the JSON data into the c# class? 如何将JSON数据转换为c#类?
你可以尝试使用
var mydata = JsonConvert.DeserializeObject<Catalogue>(jsonString);
First, your JSON is not correct. 首先,您的JSON不正确。 This is correct:
这是对的:
{
"product": [ <--- double quotes
{
"CarBrand": [
"HippoCars",
"CondorTrucks",
"CheetahMotors" <---- no trailing comma
],
"CarCategory": [
"truck",
"car",
"MotorBike"
]
} <----- closing object curly brackets
] <----- closing array square brackets
} <----- final }
Then you need to have two classes, not one: 然后,您需要有两个类,而不是一个:
public class Catalogue
{
public List<Product> product { get; set; }
}
public class Product
{
public List<string> CarBrand { get; set; }
public List<string> CarCategory { get; set; }
}
Only than you can use Json.NET as other suggested or 只有这样,您才能按照其他建议使用Json.NET或
Catalogue catalogue = new JavaScriptSerializer().Deserialize<Catalogue>(jsonString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.