2017-07-28 36 views
0

我需要從服務器返回的數據將與「數據」屬性,並返回什麼JsonConvert.SerializeObject()沒有。我如何轉換它?如何解析JSON到具有屬性的對象

來源:

{ 
    "name": "Tiger Nixon", 
    "position": "System Architect", 
    "salary": "$320,800", 
    "start_date": "2011/04/25", 
    "office": "Edinburgh", 
    "extn": "5421" 
} 

要:

{ 
    "data": [{ 
     "name": "Tiger Nixon", 
     "position": "System Architect", 
     "salary": "$320,800", 
     "start_date": "2011/04/25", 
     "office": "Edinburgh", 
     "extn": "5421" 
    }] 
} 

在VB.net(可在C#中太,我會轉換)。

+1

簡單地把你的對象陣列之前' JsonConvert.SerializeObject()' – codtex

+0

https://stackoverflow.com/questions/26795643/how-to-convert-object-containing-objects-into-array-of-objects這可能有助於 – soverflow77

回答

1

的模型。如果你開始用的一個實例你的模型類,你可以把它包裝在一個匿名的對象,並序列化:

Dim anon = New With {.data = New List(Of Model) From {model}} 
Dim json As String = JsonConvert.SerializeObject(anon, Formatting.Indented) 

小提琴:https://dotnetfiddle.net/45RtrC


如果你已經從一個JSON字符串,則可以使用變換成爲一個JObject

Dim jo As JObject = JObject.Parse(json) 
jo = New JObject(New JProperty("data", New JArray(jo))) 
json = jo.ToString() 

小提琴:https://dotnetfiddle.net/ezP6QR

1

可以將其解析到一個數組,然後序列化回來就好

Model[] data = JObject.Parse(json_string).ToObject<Model[]>(); 

考慮您已經關聯到您的JSON字符串

public class Model 
{ 
    public string name { get; set; } 
    public string position { get; set; } 
    public string salary { get; set; } 
    public string start_date { get; set; } 
    public string office { get; set; } 
    public string extn { get; set; } 
} 
+0

仍然沒有得到「名稱」propery 。現在看起來像這樣:[{「status」:2,「transactionId」:12345,「creditCardNumber」:「1234324324」,「supplier」:「Office Depot」,「createdAt」:「2008-12-28T00:00: 00" , 「量」:500.0}] –