如何将此类型的json响应转换为用户定义的类型

时间:2012-07-15 21:48:07

标签: c# json web-services api user-defined-types

我正在使用一种Web服务,它以下列格式将数据返回JSON

{
    "responseId": 2933574,
    "availableHotels": [
        {
            "processId": "HC-65870953",
            "hotelCode": "UKI9E6",
            "availabilityStatus": "InstantConfirmation",
            "totalPrice": 971,
            "totalTax": 0,
            "totalSalePrice": 0,
            "currency": "EUR",
            "boardType": "Bed & Continental Breakfast",
            "rooms": [
                {
                    "roomCategory": "Triple Room",
                    "paxes": [
                        {
                            "paxType": "Adult",
                            "age": 30
                        },
                        {
                            "paxType": "Adult",
                            "age": 30
                        },
                        {
                            "paxType": "Child",
                            "age": "6"
                        }
                    ],
                    "totalRoomRate": 486,
                    "ratesPerNight": [
                        {
                            "date": "2012-07-20",
                            "amount": 163
                        },
                        {
                            "date": "2012-07-21",
                            "amount": 163
                        },
                        {
                            "date": "2012-07-22",
                            "amount": 160
                        },
                        {
                            "date": "2012-07-23",
                            "amount": 0
                        }
                    ]
                },
                {
                    "roomCategory": "Triple Room",
                    "paxes": [
                        {
                            "paxType": "Adult",
                            "age": 30
                        },
                        {
                            "paxType": "Adult",
                            "age": 30
                        },
                        {
                            "paxType": "Child",
                            "age": "8"
                        }
                    ],
                    "totalRoomRate": 485,
                    "ratesPerNight": [
                        {
                            "date": "2012-07-20",
                            "amount": 163
                        },
                        {
                            "date": "2012-07-21",
                            "amount": 163
                        },
                        {
                            "date": "2012-07-22",
                            "amount": 160
                        },
                        {
                            "date": "2012-07-23",
                            "amount": -1
                        }
                    ]
                }
            ]
        },
        {
            "processId": "HH-22003963",
            "hotelCode": "UKPDNN",
            "availabilityStatus": "InstantConfirmation",
            "totalPrice": 1085,
            "totalTax": 0,
            "totalSalePrice": 0,
            "currency": "EUR",
            "boardType": "Bed and Breakfast",
            "rooms": [
                {
                    "roomCategory": "Triple Room",
                    "paxes": [
                        {
                            "paxType": "Adult",
                            "age": 30
                        },
                        {
                            "paxType": "Adult",
                            "age": 30
                        },
                        {
                            "paxType": "Child",
                            "age": "6"
                        }
                    ],
                    "totalRoomRate": 544,
                    "ratesPerNight": [
                        {
                            "date": "2012-07-20",
                            "amount": 136
                        },
                        {
                            "date": "2012-07-21",
                            "amount": 136
                        },
                        {
                            "date": "2012-07-22",
                            "amount": 136
                        },
                        {
                            "date": "2012-07-23",
                            "amount": 136
                        }
                    ]
                },
                {
                    "roomCategory": "Triple Room",
                    "paxes": [
                        {
                            "paxType": "Adult",
                            "age": 30
                        },
                        {
                            "paxType": "Adult",
                            "age": 30
                        },
                        {
                            "paxType": "Child",
                            "age": "8"
                        }
                    ],
                    "totalRoomRate": 541,
                    "ratesPerNight": [
                        {
                            "date": "2012-07-20",
                            "amount": 136
                        },
                        {
                            "date": "2012-07-21",
                            "amount": 136
                        },
                        {
                            "date": "2012-07-22",
                            "amount": 136
                        },
                        {
                            "date": "2012-07-23",
                            "amount": 133
                        }
                    ]
                }
            ]
        }
    ],
    "totalFound": 2,
    "searchId": "QG-67623913"
}

现在我的课程定义如下:

 public class getAvailableHotelResponse
    {
        public getAvailableHotelResponse();

        public hotel[] availableHotels { get; set; }
        [SoapElement(DataType = "integer")]
        public string responseId { get; set; }
        public string searchId { get; set; }
        [SoapElement(DataType = "integer")]
        public string totalFound { get; set; }
    }

hotel类如下:

public class hotel
    {
        public hotel();

        public string availabilityStatus { get; set; }
        public string boardType { get; set; }
        public string currency { get; set; }
        public string hotelCode { get; set; }
        public string processId { get; set; }
        public roomResponse[] rooms { get; set; }
        [SoapElement(DataType = "integer")]
        public string specialDeal { get; set; }
        public float totalPrice { get; set; }
        [SoapIgnore]
        public bool totalPriceSpecified { get; set; }
        public float totalSalePrice { get; set; }
        [SoapIgnore]
        public bool totalSalePriceSpecified { get; set; }
        public float totalTax { get; set; }
        [SoapIgnore]
        public bool totalTaxSpecified { get; set; }
    }

roomResponse类如下:

public class roomResponse
    {
        public roomResponse();

        public pax[] paxes { get; set; }
        public dailyRate[] ratesPerNight { get; set; }
        public string roomCategory { get; set; }
        public float totalRoomRate { get; set; }
        [SoapIgnore]
        public bool totalRoomRateSpecified { get; set; }
    }

pax类如下:

 public class pax
    {
        public pax();

        [SoapElement(DataType = "integer")]
        public string age { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string paxType { get; set; }
        public string title { get; set; }
    }

dailyRate类如下:

 public class dailyRate
    {
        public dailyRate();

        public float amount { get; set; }
        [SoapIgnore]
        public bool amountSpecified { get; set; }
        [SoapElement(DataType = "date")]
        public DateTime date { get; set; }
        [SoapIgnore]
        public bool dateSpecified { get; set; }
    }

修改

getAvailableHotelResponse h = new getAvailableHotelResponse();

h = (getAvailableHotelResponse)Newtonsoft.Json.JsonConvert.DeserializeObject(text);

我尝试了这个,它引发了以下错误:

  

无法将类型为“Newtonsoft.Json.Linq.JObject”的对象强制转换为类型   'hotelspro.getAvailableHotelResponse'。

JSON的结构非常复杂,所以如何将其转换为我的对象?

2 个答案:

答案 0 :(得分:6)

删除不可编译的构造函数,例如public pax();,然后使用

var availHotels = JsonConvert.DeserializeObject<getAvailableHotelResponse>(text);

就是这样。

实际上,您甚至不需要声明这一类(getAvailableHotelResponsehotelroomResponsepaxdailyRate等。 )如果你使用dynamic。例如,

dynamic response = Newtonsoft.Json.JsonConvert.DeserializeObject(text);

foreach (var hotel in response.availableHotels)
{
    Console.WriteLine(hotel.processId);
    foreach (var room in hotel.rooms)
    {
        Console.WriteLine("\t" + room.roomCategory);
    }
}

答案 1 :(得分:4)

大多数时候,当我处理提供响应的框架时,他们至少都有标准化的响应。

什么样的回应可能是通用的,但我知道会发生什么。因此,收到广泛的回应并不罕见,例如:

{
   'data': 'JSON-blah-JSON-blah-IneedAcocktail-JSON-blah',
   'status': 200,
   'fortune': 'shakeHarder'
}

了解该泛型响应然后使用它来反映您以后需要的内容可能就是这种情况。

例如,您收到的所有对象都是您已经使用过的对象。可能有一些事情,例如你通常不知道的pax号码......继续它和其他不需要冲突的标准化随机事物。

然后创建一个包含所需对象的容器类。也许您需要将其翻译成您的格式;但至少你有你知道如何使用的格式,并且在你是蓝色之前你不会解析字符串。