0

I'm working on a product in VB.NET and using the JSON class from NewtonSoft to process JSON. I don't know how to use it though and I can't seem to figure ou the doc. Basically, given a JSON string, I want to pull out the amount value. Here's what I have:

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)

Now, at this point, I was hoping to be able to do a

amountHeld = jsonObject.Name["amount"]

to get the value of amount but I can't. I'm obviously doing it wrong. What is the proper way to do this?

Thanks! Anthony

2
  • What is the value of serverResponse? Just put a breakpoint at amountHeld line of code and inspect the value of jsonObject. Commented Jan 16, 2014 at 0:18
  • serverResponse holds the JSON string the server returns. I've validated that. The problem I have is that I know how to assign it to jsonObject but not how to retrieve a specific key. Commented Jan 16, 2014 at 0:20

2 Answers 2

2

You can use json.net to deserialize into a specific type, or an anonymous type, like this:

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)

This creates an anonymous type with the property 'amountHeld' which json.net then uses to deserialize the json into.

An alternative approach would be to use Linq 2 JSON to parse the json and extract the values you want out of it similar to 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)

The JObject classes are in the Newtonsoft.Json.Linq namespace

Here is some more info on linq 2 json, unfortunately all the examples are in C#, but it might help you with what can and can't be done

Sign up to request clarification or add additional context in comments.

Comments

0

Try it this way

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

1 Comment

Ok so I see where you're going with it and that's actually the way I though it would be done. But I can't seem to actually FIND System.Json to use the class. Where is it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.