2014-01-16 122 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

相关问题