C# JavaScriptSerializer不将Json字符串转换为对象?
下面的代码不会返回任何错误,但仍然不会将JSON转换为对象 我从API获得的JSON字符串C# JavaScriptSerializer不将Json字符串转换为对象?,c#,asp.net,api,serialization,jsonserializer,C#,Asp.net,Api,Serialization,Jsonserializer,下面的代码不会返回任何错误,但仍然不会将JSON转换为对象 我从API获得的JSON字符串 { "genres": [ { "id": 28, "name": "Action" }, { "id": 12, "name": "Adventure" } ] } 普通考试班 public class Test
{
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 12,
"name": "Adventure"
}
]
}
普通考试班
public class Test
{
public int id;
public string Name;
}
下面的代码显示了我如何尝试将JSON字符串转换为测试类列表
string JsontStr = GenreService.get();
var Serializer = new JavaScriptSerializer();
List<Test> a = (List<Test>)Serializer.Deserialize(JsontStr, typeof(List<Test>));
string JsontStr=GenreService.get();
var Serializer=新的JavaScriptSerializer();
lista=(List)序列化程序。反序列化(JsontStr,typeof(List));
序列化程序不工作,因为json不是测试对象的数组。它实际上是一组类型元素。在测试类中,名称必须是小写,才能与json字符串中的大小写匹配
public class Test
{
public int id {get;set;}
public string name {get;set;} // it should be all lowercase as well. Case matters
}
public class Genres
{
public List<Test> genres {get;set;}
}
string JsontStr = GenreService.get();
var Serializer = new JavaScriptSerializer();
Genres a = (Genres)Serializer.Deserialize(JsontStr, typeof(Genres));
公共类测试
{
公共int id{get;set;}
公共字符串名称{get;set;}//也应该是小写的。大小写很重要
}
公共类体裁
{
公共列表类型{get;set;}
}
字符串JsontStr=GenreService.get();
var Serializer=新的JavaScriptSerializer();
类型a=(类型)序列化程序。反序列化(JsontStr,typeof(类型));
我用网络方法对你的案例做了一个小测试,并且@Jawad的答案是正确的
测试对象列表的答案是类型,这是我从测试中得到的结果
genres: [{id: 28, name: "Action"}, {id: 12, name: "Adventure"}]
因此,我只需要声明这样的WebMethod
[WebMethod]
public static int JSONApi(List<Test> genres)
[WebMethod]
公共静态int-JSONApi(列表类型)
序列化是自动完成的
希望这有助于澄清您的情况。用于生成正确的数据模型。您需要一个根对象public类Welcome{public List Genres{get;set;}}
,如中所示,这是链接问题答案中提到的工具之一。