2017-07-25 50 views
0

我有一個element類,它包含一個options財產,期權類又可以改變其屬性,例如可能有這2反序列化動態屬性在ASP.net Web的API

Element1 = { 
    "Id": "1", 
    "Options": { 
     "Printable": "true", 
     "StackOverflow": "great" 
    } 
} 

Element2 = { 
    "Id": "2", 
    "Options": { 
     "Question": "awsome", 
     "PropertyDiferent": "empty" 
    } 
} 

在網頁API我有一個這樣的方法:

Public object Post ([FromBody] Element element) 
{ 
    SaveToMongo (element); 
} 

元素類:

Public class Element 
{ 
    Public dynamic options {get; set; } 
    Public string id {get; set; } 
} 

當我從Mongo拿起元素時,我沒有任何問題。但是,當我使用Api web的post方法發送它時,它並不反序列化它自己,在expando對象中,因爲它是從Mongo開始的。我怎麼能在兩端得到類似的行爲?

編輯:我試圖將選項從動態更改爲newtonsoft JObject,但它沒有奏效。現在選項也得到了保存,但是他們生成了我不想要的父親。

"options" : { 
      "_t" : "Newtonsoft.Json.Linq.JObject, Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed", 
      "_v" : { 
       "padding" : { 
        "_t" : "JArray", 
        "_v" : [ 
         { 
          "_t" : "JValue", 
          "_v" : [ 

          ] 
         }, 
         { 
          "_t" : "JValue", 
          "_v" : [ 

          ] 
         }, 
         { 
          "_t" : "JValue", 
          "_v" : [ 

          ] 
         }, 
         { 
          "_t" : "JValue", 
          "_v" : [ 

          ] 
         } 
        ] 
       }, 
       "image" : { 
        "_t" : "JValue", 
        "_v" : [ 

        ] 
       }, 
       "alt" : { 
        "_t" : "JValue", 
        "_v" : [ 

        ] 
       }, 
       "url" : { 
        "_t" : "JValue", 
        "_v" : [ 

        ] 
       }, 
       "width" : { 
        "_t" : "JValue", 
        "_v" : [ 

        ] 
       }, 
       "backgroundColor" : { 
        "_t" : "JValue", 
        "_v" : [ 

        ] 
       }, 
       "text" : { 
        "_t" : "JValue", 
        "_v" : [ 

        ] 
       } 
      } 
     }, 

有更多的屬性,因爲我直接從mongo中提取示例。

+0

你可以使用Newtonsoft.Json的JObject而不是動態的嗎? –

+0

@PedroDrewanz我會嘗試一下。因爲這幾天我的一些問題都是失敗的。 –

回答

0

第一步,使來自javascript的ajax調用將JSON作爲字符串傳遞,否則不會填充動態屬性選項。

Element.options = element.options.toString(); 

所以我有一個JSON字符串,雖然它存儲在mongo中,我可以在不修改的情況下恢復它。但是爲了能夠在Api中返回它,我必須在控制器本身完成反序列化之前將其反序列化。

Element.options = JObject.Parse (element.options); 

這是一個uncool系統,有一些缺點,因爲它不允許mongo中的選項的處理。但是,這一直是我設法蒙戈的通道沒有改變目標的唯一方法。