2013-01-25 31 views
0

您好我正在嘗試創建web api,我可以調用它來查看MongoDB中的所有文檔,現在這些文檔非常大並且嵌套嚴重,我已經管理返回該文檔,但在Json中使用XML中的標題。Web API返回XML和Json,只希望Json

我需要在Json中返回這整個東西!

這個代碼利用BsonDocument產品因爲沒有這個,我得到一個錯誤返回此爲JSON:

[JsonIgnore] 
     public BsonDocument Product { get; set; } 

[DataMember] 
     public string Product 
     { 
      get { return Product .ToJson(); } 
      set { Product = BsonDocument.Parse(value); } 
     } 

這裏是文檔(這是一個基本的例子的樣本,實際的文件要大得多有更深層次:

{ 
    "product": { 
     "Type": "Phone", 
      "Size": { 
      "Height": 10, 
       "Lenght": 5, 
       "Weight": 30 
     } 
     "Make": "Apple" 
     "Model": { 
      "Name": "IPhone", 
       "Range": "4s" 
     } 

    } 
} 

返回作爲

<Product> 
{"product": {"Type": "Phone","Size": {"Height": 10,"Lenght": 5,"Weight": 30}"Make": "Apple", "Model": {"Name": "IPhone","Range": "4s"}}} 
</Product> 

如何我解決這個問題嗎?

回答

1

How do i fix this?

像這樣:

public HttpResponseMessage Get() 
{ 
    MyViewModel model = ... 
    // This will contain the JSON you want to return to the client 
    string product = model.Product; 

    var response = new HttpResponseMessage(); 
    response.Content = new StringContent(product, Encoding.UTF8, "application/json"); 
    return response; 
} 
+0

感謝您的迅速反應,我把這個包含在我的問題的代碼的第一個片段我的產品類別? –

+1

不,你把這個放在你的Web API控制器動作中,這個動作應該是服務這個JSON的。 –

+0

我明白了,那麼MyViewModel會是什麼? –