反序列化对象结果为空变量C#
我试图从下面的JSON响应中提取反序列化对象结果为空变量C#,c#,json,visual-studio,C#,Json,Visual Studio,我试图从下面的JSON响应中提取“name”和“score”的值: "categories": [ { "name": "people_", "score": 0.6640625 }, { "name": "people_portrait", "score": 0.33203125 } ] 我目前的C#代码是: public class Category { public string
“name”
和“score”
的值:
"categories": [
{
"name": "people_",
"score": 0.6640625
},
{
"name": "people_portrait",
"score": 0.33203125
}
]
我目前的C#代码是:
public class Category
{
public string name { get; set; }
public double score { get; set; }
}
string contentString=wait response.Content.ReadAsStringAsync();
var r=JsonConvert.DeserializeObject(contentString);
控制台写入线(r.name);
控制台写入线(r.score);
Console.ReadLine();
但当我尝试将结果打印到控制台时,会给出一个空白响应。我还检查了调试器,name
用null
填充,score
用0
填充
在此方面的任何帮助都将不胜感激 在json字符串中,
categories
是一个JObjects
的列表,因此您可以使用@Roman的方法来解决您的问题或尝试我的方法
这是我的方法
创建一个名为Categories的根类
public class Categories
{
[JsonProperty(PropertyName = "categories")]
public List<Category> ListOfCategory {get; set;}
}
现在,使用下面的代码反序列化
var categories = JsonConvert.DeserializeObject<Categories>(contentString);
POC:您应该反序列化列表而不是单个类别如果属性具有相同的属性,您实际上不需要属性JsonPropertyname@RomanMarusyk,我理解您的评论,并相应地更新了我的代码
public class Category
{
public string Name { get; set; }
public double Score { get; set; }
}
var categories = JsonConvert.DeserializeObject<Categories>(contentString);
foreach(var item in categories.ListOfCategory)
{
Console.WriteLine($"Name : {item.Name} \t Score: {item.Score}");
}