【问题标题】:JavaScriptSerializer does not convert Json string to object? [closed]JavaScriptSerializer 不会将 Json 字符串转换为对象? [关闭]
【发布时间】:2020-03-30 21:52:35
【问题描述】:

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

我从 API 获得的 JSON 字符串

{
    "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>));

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

【问题讨论】:

标签: c# asp.net api serialization jsonserializer


【解决方案1】:

序列化程序不工作,因为 json 不是 Test 对象的数组。它实际上是一个流派元素数组。在您的测试类中,名称必须小写才能匹配 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));

【讨论】:

    【解决方案2】:

    我用 WebMethod 对你的情况做了一个小测试,@Jawad 的答案是正确的。

    测试对象列表的答案是Genres,这是我从我做的测试中得到的

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

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

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

    并且序列化是自动完成的

    希望它有助于澄清你的情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 2018-05-09
      • 1970-01-01
      • 2019-08-27
      • 2020-05-27
      相关资源
      最近更新 更多