2012-12-20 43 views
4

我正在使用Json.NET創建json的結構可能更改的定義。因此,我無法簡單地序列化一個類,並使用Json轉換Linq來即時創建結構。我在使用JObject,JArray,JProperty,創建下面的結構問題等如何在json.net中使用json創建字典結構linq

{ 
    'external_id':'UNIQUE_ID_222222222', 
    'firstname':'John', 
    'lastname':'Smith', 
    'customFields': 
     { 
     'custom1':'custom1 val', 
     'custom2':'custom2 val', 
     'custom3"':'custom3 val' 
     } 
    } 

我用下面的代碼嘗試:

Dim json As New JArray() 
Dim jsonObj As New JObject(_ 
      New JProperty("external_id", "UNIQUE_ID_222222222"), 
      New JProperty("firstname", "John"), 
      New JProperty("lastname", "Smith")) 

Dim jsonCustomFields As New JArray 
Dim jsonCustomObject As New JObject 

jsonCustomFields.Add(jsonCustomObject) 

For Each field In CustomFieldList 
    jsonCustomObject.Add(New JProperty(field.Label, field.Value)) 
Next  

jsonObj.Add(New JProperty("customFields", jsonCustomFields)) 
json.Add(jsonContrib) 

但是當我這樣做,我得到一個不同的模式,這是不接受的web服務

{[ 
    { 
    "external_id": "50702", 
    "firstname": "John", 
    "lastname": "Smithson", 
    "customFields": [ 
     { 
     "custom1":"custom1 val", 
     "custom2":"custom2 val", 
     "custom3":"custom3 val" 
     } 
    ] 
    } 
]} 

我認爲我應該直接添加屬性到JArray,但這樣做會導致運行時異常。

我看到了一個類似的模式,當你反序列化一個字典(字符串,字符串)對象時創建,但我真的不想將我的自定義字段添加到字典,然後反序列化它們。必須可以使用上述符號創建它們。

回答

3

你並不需要一個JArray,而是使用JObject

下面的代碼是C#,但你將能夠找出

JObject jObject = new JObject(); 
jObject.Add(new JProperty("external_id", "UNIQUE_ID_222222222")); 
jObject.Add(new JProperty("firstname", "John")); 
jObject.Add(new JProperty("lastname", "Smith")); 

JObject customFields = new JObject(); 
//Your loop 
customFields.Add("custom1", "custom1 val"); 
customFields.Add("custom2", "custom2 val"); 
customFields.Add("custom3", "custom3 val"); 

jObject.Add(new JProperty("customFields", customFields)); 

讓我知道這個工程或不

+0

謝謝。這確實有效。我想我很困惑,當我看到迭代屬性列表並自動假定「數組」 – zeiddev