将json字符串转换为CLR类型

时间:2013-08-07 12:16:58

标签: c# json

我跟随json stirng

{
"api_version" : 2 ,
"lang" : "en_US",
"hotels" :
[
{
"hotel_id" : 258705 ,
"desc" : "The Hotel Commonwealth stands above the Kenmore Square \"T\" subway station in Boston, Mass. Fenway Park is located two blocks away, while the shops along Newbury Street are three blocks from the hotel.",
"amenities" : ["RESTAURANT","NON_SMOKING"],
"room_types" :
{
"Fenway Room" :
{
"url" : "http://www.partnersite.com/hotel_commonwealth/fenway_room",
"desc" : "One king bed with pillowtop mattress, Frette Italian linens, down bedding, multiple pillows. View of Fenway Park."
},
"Commonwealth Room" :
{
"url" : "http://www.partnersite.com/hotel_commonwealth/commonwealth_room",
"desc" : "One king bed with pillowtop mattress, Frette Italian linens, down bedding, multiple pillows. View of Commonwealth Avenue."
}
}
}
]
}

我创建了以下poco类。我可以使用NewtonSoft反序列化上面的字符串。

internal class FenwayRoom
    {    

    }

    internal class CommonwealthRoom
    {

    }

    internal class RoomTypes
    {

        [JsonProperty("Fenway Room")]
        public FenwayRoom FenwayRoom { get; set; }

        [JsonProperty("Commonwealth Room")]
        public CommonwealthRoom CommonwealthRoom { get; set; }
    }

    internal class Hotel
    {


    }

}

现在的问题是,对于每个房型,我都要创建一个隔间类。是否有更好的方法呢?

2 个答案:

答案 0 :(得分:1)

每个房间的属性看起来都是一样的,你只需要引入一个Room类,例如。

public class Room
{
    [JsonProperty("url")]
    public string Url { get; set; }
    [JsonProperty("desc")]
    public string Description { get; set; }
}

public class RoomTypes
{
    [JsonProperty("Fenway Room")]
    public Room FenwayRoom { get; set; }
    [JsonProperty("Commonwealth Room")]
    public Room CommonWealthRoom { get; set; }
}

答案 1 :(得分:0)

您可以使用以下自动化工具:

JSON TO CSHARP

JSONPACK