JavaScriptSerializer不能将Json字符串转换为对象吗?

下面的代码不会返回任何错误,但仍不会将JSON转换为对象

我从API获得的

JSON字符串

{
    "genres": [
        {
            "id": 28,"name": "action"
        },{
            "id": 12,"name": "Adventure"
        }
    ]
}

一般考试班

    public class Test
    {
        public int id;
        public string Name;
    }

下面的代码显示了我如何尝试将JSON字符串转换为Test类的列表

            string JsontStr = GenreService.get();
            var Serializer = new JavaScriptSerializer();
            List<Test> a = (List<Test>)Serializer.Deserialize(JsontStr,typeof(List<Test>));

an image of what the object a has in it when the program has finished running

study222 回答:JavaScriptSerializer不能将Json字符串转换为对象吗?

序列化程序不起作用,因为json不是Test对象的数组。它实际上是Genres元素的数组。在测试类中,名称必须小写以匹配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));
,

我用 WebMethod 对您的情况做了一些测试,而@Jawad的回答很严格。

测试对象列表的答案是流派,这就是我从测试中获得的信息

genres: [{id: 28,name: "Action"},{id: 12,name: "Adventure"}]

因此,我只需要声明一个这样的WebMethod

[WebMethod]
public static int JSONApi(List<Test> genres)

并且序列化是自动完成的

希望这有助于弄清您的情况。

本文链接:https://www.f2er.com/2966639.html

大家都在问