我要求序列化我的C#类RoomType,如下所示
public class RoomType
{
public string name { get; set; }
public string url { get; set; }
public string desc { get; set; }
}
以下json格式
"room_types" :
{
"Fenway Room" :
{
"url" : "http://www.partner-site.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.partner-site.com/hotel_commonwealth/commonwealth_room",
"desc" : "One king bed with pillowtop mattress, Frette Italian linens, down bedding, multiple pillows. View of Commonwealth Avenue."
}
}
如何以这种json格式获取“Fenway Room”和“Commonwalth Room”?
我尝试了这个建议,但仍然无法得到匿名符合我在ActionResult中所需的内容。这是我现在不能正常工作的代码:
var rooms = new List<HarRoomType>()
{
new HarRoomType()
{
}
};
var anonymous = new
{
type = rooms.ToDictionary(x => x.name, x => new {x.currency, x.discounts})
};
var response = new HotelAvailabilityResponse()
{
api_version = 4,
hotel_ids = new List<int>()
{
1,
2
},
start_date = "2014-02-21",
hotels = new List<HarHotel>()
{
new HarHotel()
{
hotel_id = 1,
room_types = anonymous
},
new HarHotel()
{
hotel_id = 2,
room_types = new List<HarRoomType>()
}
}
};
return Json(response, JsonRequestBehavior.AllowGet);
答案 0 :(得分:1)
您需要将数据整形为字典:
RoomType[] rooms = ...
var serializeThis = new {
room_types = rooms.ToDictionary(
x => x.name,
x => new { x.url, x.desc }
)
};
答案 1 :(得分:0)
JavaScriptSerializer js = new JavaScriptSerializer();
List<RoomType> roomTypes = new List<RoomType>(){
new RoomType{ desc="desc 1", name="Fenway Room", url="blah.com"},
new RoomType{ desc="desc 2", name="Commonowealth Room", url="blah.com"},
};
如果您不关心将名称显示为属性,那么:
var json = js.Serialize(roomTypes.ToDictionary(x => x.name));
如果您 关心是否显示该名称并且不希望它出现:
var json2 = js.Serialize(roomTypes.ToDictionary(x => x.name, x => new { desc = x.desc, url = x.url }));
答案 2 :(得分:0)
使用此:
var anonymous= new {
type= rooms.ToDictionary(
x => x.name,
x => new { x.url, x.desc }
)