2014-02-13 50 views
2

我的要求連載我的C#類RoomType像下面序列化的Json與變量名

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." 
     } 
    } 

如何得到「芬威房「」Commonwalth Room「以這種json格式?

我試過這個建議,但仍然無法得到匿名適合我需要的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); 

回答

1

你需要的形狀數據作爲詞典:

RoomType[] rooms = ... 

var serializeThis = new { 
    room_types = rooms.ToDictionary(
     x => x.name, 
     x => new { x.url, x.desc } 
    ) 
}; 
+0

哪有這個工作在ASP MVC?我更新了一個代碼,我需要在ASP MVC –

+0

@JeeShenLee,應該在MVC工作正常。如果你看到一個特定的問題,你需要告訴我它說 –

+0

更新了這個問題。在room_types =匿名獲取對象不兼容的問題 –

1
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 })); 
0

使用此:

var anonymous= new { 
    type= rooms.ToDictionary(
     x => x.name, 
     x => new { x.url, x.desc } 
    )