1

I'm trying to deserialize a JSON string and then loop through it's results. I started here: http://www.newtonsoft.com/json/help/html/QueryJsonLinq.htm

I want to translate that to a VB.NET version, but I'm getting all sorts of errors. I tried several translators without luck (such as http://converter.telerik.com/).

JSON string

{
    "responseHeader": {
        "status": 0,
        "QTime": 1,
        "params": {
            "sort": "title asc"
            "rows": "10"
        }
    },
    "response": {
        "numFound": 3,
        "start": 0,
        "docs": [{
            "title": "Amsterdam",
            "cityurl": "amsterdam"
        }, {
            "title": "London",
            "cityurl": "london"
        }, {
            "title": "New York",
            "cityurl": "new-york"
        }]
    }
}

First I'm trying to deserialize the JSON:

Dim postTitles = From p In rss("channel")("item")DirectCast(p("title"), String)
'End of Statement Expected on `DirectCast(p("title"), String)`

Then I try to loop through the results, but both ways I've tried below don't work

For Each item As var In postTitles
    Log("title", item)
Next
'type 'var' is not defined

For Each (dim item In postTitles)
    Log("title", item)
Next
'Expression expected (on `dim`)

What is the correct code in VB.NET to do this?

1 Answer 1

1
Dim data As JObject = JObject.Parse(json)

Dim postTitles = From doc In data("response")("docs")
                 Select doc("title").Tostring()

For Each item In postTitles
    Log("title", item)
Next

Reference: Introduction to LINQ in Visual Basic

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

2 Comments

Thanks! With your code I get the design time error Value of type 'Newtonsoft.Json.Linq.JToken' cannot be converted to 'String'. on part doc("title"). I had to change that to doc("title").ToString, does that matter? It does generate the correct output now :)
@Flo, if this solves the issue related to your question, you can mark it as the answer. Thanks.

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.