JavaScriptSerializer.Deserialize提供Null字段

本文关键字:字段 Null 提供 Deserialize JavaScriptSerializer | 更新日期: 2023-09-27 18:29:22

我向接受Stream作为参数的WCF服务发送了以下JSON。

{"ReservationStream":
{"clientFirstName":"Abe",
"clientLastName":"Lincoln",
"clientPhone":"0544944860",
"clientEmail":"abe@mail.com",
"pickupLocationID":"3699",
"pickupAddressString":"JFK Airport Terminal 1",
"pickupFlightNumber":"LY001",
"pickupAirline":"El Al",
"pickupAirportName":"John F Kennedy Intl",
}
}

在调试器中,流变量按预期显示所有值。我想反序列化为一个定义如下的类:

public class ReservationStream
{
        public String clientFirstName { get; set; }
        public String clientLastName { get; set; }
        public String clientPhone { get; set; }
        public String clientEmail { get; set; }
        public String pickupLocationID { get; set; }
        public String pickupAddressString { get; set; }
        public String pickupFlightNumber { get; set; }
        public String pickupAirline { get; set; }
        public String pickupAirportName { get; set; }
}

当我呼叫时

 JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            ReservationStream structuredReservations = javaScriptSerializer.Deserialize<ReservationStream>(strJSON);

不会引发异常,但所有字段都具有null值。我的错误在哪里?

JavaScriptSerializer.Deserialize提供Null字段

我认为这是因为JSON对象嵌套在ReservationStream标记中。

试试看:

{ "clientFirstName":"Abe", "clientLastName":"Lincoln", "clientPhone":"0544944860", "clientEmail":"abe@mail.com", "pickupLocationID":"3699", "pickupAddressString":"JFK Airport Terminal 1", "pickupFlightNumber":"LY001", "pickupAirline":"El Al", "pickupAirportName":"John F Kennedy Intl" }

您正试图反序列化包含ReserveStream对象的对象,而不是ReserveStream对象本身。

解决这个问题的一种方法是创建一个包含ReserveStream的包装类,并使用以下方法进行反序列化:

public class WrapperClass
{
    public ReservationStream ReservationStream { get; set; }
}
WrapperClass wrapperClass = serializer.Deserialize<WrapperClass>(strJSON);

我曾经遇到过同样的问题,我删除了javaScriptSerializer并直接使用了类似的方法参数

public static string UpdateTemplateProperties(TemplateProperties templateProperties)
{
    var x = templateProperties.Something
}

我有javascript对象结构作为

只需确保参数的名称和javascript对象文字中的第一个对象名称相同