2014-01-16 123 views
0

我正在使用VB.NET中的產品,並使用NewtonSoft的JSON類來處理JSON。我不知道如何使用它,但我似乎無法確定文檔。基本上,給定一個JSON字符串,我想提取金額值。下面是我有:如何使用NewtonSoft的JSON類反序列化JSON對象?

Dim serverResponse as String 
Dim urlToFetch as String 
Dim jsonObject as Newton.JSON.JSONConvert 
Dim wc as new System.Net.WebClient 
Dim amountHeld as String 

urlToFetch = "someurl" 
serverResponse = wc.DownloadString(urlToFetch) 
jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(serverResponse) 

現在,在這一點上,我希望能夠做一個

amountHeld = jsonObject.Name["amount"] 

獲得量的價值,但我不能。我顯然是做錯了。什麼是正確的方法來做到這一點?

謝謝! 安東尼

+0

什麼是'serverResponse'的價值?只需在'amountHeld'行代碼處添加一個斷點並檢查'jsonObject'的值。 – Styxxy

+0

serverResponse保存服務器返回的JSON字符串。我已經驗證了這一點。我遇到的問題是我知道如何將其分配給jsonObject,但不知道如何檢索特定的鍵。 – CajunTechie

回答

2

您可以使用json.net反序列化到一個特定的類型,或者匿名類型,像這樣:

Dim serverResponse as String 
Dim jsonObject as object 
Dim amountHeld as String 

serverResponse = "{amountheld: ""100""}" 

Dim deserializedResponse = New With {.amountHeld = "1" } 

jsonObject = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(serverResponse, deserializedResponse) 

Console.WriteLine(jsonObject.amountHeld) 

這將創建一個匿名類型與財產'amountHeld'哪json.net然後用於反序列化json到。

另一種方法是使用LINQ的2 JSON解析JSON並提取你想從它的值類似於LINQ 2 XML:

Dim serverResponse as String 
Dim jsonObject as object 
Dim amountHeld as String 

serverResponse = "{amountheld: ""100""}" 

Dim o as JObject = JObject.Parse(serverResponse) 

amountHeld = o.item("amountheld").ToString() 

Console.WriteLine(amountHeld) 

的JObject類在Newtonsoft.Json。 LINQ的命名空間

Here是LINQ 2 JSON一些更多的信息,遺憾的是所有的例子都是在C#中,但又能怎樣它可能會幫助你,不能做

0

嘗試這種方式

var jsonObject = JsonObject.Parse(serverResponse); 
var amount= jsonObject.GetNamedString("amount"); 
+0

好吧,讓我看看你要去的地方,這實際上就是我做這件事的方式。但我似乎無法真正發現System.Json使用該類。它在哪裏? – CajunTechie

相關問題