2017-10-16 123 views
0

如何創建一個數組,如果我們轉換成json,我們會得到下面的結果。在vb.net 2010中創建一個多維數組

{{"name":"first_example_1"}, {"name": "second_example_1"}} 

我試圖用這個

dim x as jArray 
x.add("first_example_1") 
x.add("second_example_1") 

,但是當我嘗試將上述以JSON我得到這個

{"firstname_example_1", "second_example_1"} 

我如何添加一個索引?

回答

1

試試這個

 Dim jArray(1) As Object 
     jArray(0) = New With {Key .name = "second_example_1"} 
     jArray(1) = New With {Key .name = "firstname_example_1"} 
     Dim serializer As New JavaScriptSerializer() 
     Dim result As String 
     result = serializer.Serialize(jArray) 

,不要忘了Imports System.Web.Script.Serialization

+0

我在閱讀您的答案之前更改了我的代碼。根據我的問題,你的代碼工作,併產生我想要的確切結果,很酷。但是由於我的引用中沒有system.web.script.serialization,所以我很難對這個對象進行反序列化(「因爲我是VB.net上的新手」),我不知道爲什麼我可以'在我的參考資料上找到它,我只有system.web.services。謝謝你,先生。我很感激。 –

0

@styx作品上面的答案,但我已經改變我的代碼。這個答案僅供參考。

我創建了一個名爲PerInfo

public class PerInfo 
    public firstname 
    public lastname 
end class 

要序列化,我寫這個類;

dim x as new PerInfo 
x.firstname = textbox1.text 
x.address = textbox2.text 

dim res as string = JsonConvert.SerializeObject(x) 
' the above code produces my desired result which is 
' {"firstname":"jeo","address":"GSC"} 

要反序列化,我做了這個;

Dim t As PerInfo = JsonConvert.DeserializeObject(Of PerInfo)(x) 
'I can now access the `firstname` and `address` via 
' t.firstname and t.address 

MsgBox(t.firstname & "===" & t.address) 

希望這有助於...

PS:我通過添加引用手動添加的Newtonsoft.Json.dll 版本Net 2.0爲使用.net 2.0框架,如果我是對PC的向後兼容性。隨意糾正我這一點。