0

My problem is as follows:

I have a Public sub created which looks like this for the moment:

Public Sub eniroContacts()
        Dim phone As String = newCustPhone1.text
        Dim url As String = "http://bedrift.telefonkatalogen.no/tk/search.php?qry=" + phone + "&from=1&to=27&format=json&username=user&password=pw"
        Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
        Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
        Dim reader As StreamReader = New StreamReader(response.GetResponseStream())
        Dim o As JObject = JObject.Parse(reader.ReadToEnd)

        lblMsg.Text = o.ToString

        reader.Close()
        response.Close()
    End Sub

so far so good and my lblMsg.Text displays the json string i want to get my data from (formatted for clarity):

{
    "qry": "92020945",
    "result": {
        "hitLinesBeforeFilter": 1,
        "userID": 299228,
        "1": {
            "listing": {
                "table": "listing",
                "id": "3647950",
                "duplicates": [{
                    "table": "listing",
                    "id": "3647950:0",
                    "idlinje": "E19CMOD",
                    "tlfnr": "99887766",
                    "etternavn": "Omnes",
                    "fornavn": "Martin",
                    "veinavn": "Highway",
                    "husnr": "20",
                    "postnr": "0601",
                    "virkkode": "P",
                    "apparattype": "M",
                    "telco": "TM",
                    "kilde": "E",
                    "bkdata": "M",
                    "prioritet": "0",
                    "fodselsdato": "1976-07-03",
                    "kommunenr": "301",
                    "poststed": "Oslo",
                    "kommune": "Oslo",
                    "fylke": "Oslo",
                    "landsdel": "Ø"
                }]
            }
        },
        "dummy": null
    }
}

What I want to do now is to actually fetch some of the values in the string and put them into some of my textboxes and labels, but don't have a clue on how can I do that. For example, I would want the values "fornavn", "tlfnr" and "fylke". The values are Martin, 99887766 and Oslo in this example, which should be put in textbox1, 2 and 3.

Also i would like to add that some of the Fields may not be there on some searched, like the first name ("fornavn" in my example). When this isnt there and i try writing:

 Dim fornavn = o("result")("1")("listing")("duplicates")(0)("fornavn")

it crashes. Something i can do to prevent this in these scenarios?

Any clues and tips are very appreciated! :)

Martin
  • 39
  • 7

1 Answers1

0

The easiest thing would be using directly the property names and array indexes (from json.net docs). Something like this:

Dim fornavn = o("result")("1")("listing")("duplicates")(0)("fornavn")

It looks like the number of results and duplicates in the response will change between different responses, so you may not be able to hardcode it like that (For example, you may need to check first that result has at least one item and also that duplicates has at least one item)

Another approach would be to deserialize the string into strongly typed .Net objects. You would create your .Net classes that mirror the json structure and tell json.net to convert the json string into .Net object instances of those classes. See the json.net docs. This requires more work as you need to create the .Net classes and you will need to understand the deserialization process. If you want to explore this option, have a look at this and this other questions.

Edit

Given the json structure, it might be easier to manually get the properties like "1" inside the result property in the json object. Then you have the options to either manually continue drilling in the object and iterating over the duplicates, applying whatever logic you require, or deserialize into .Net objects.

The following code will get the result property, iterate over all its properties with keys 1,2, etc and print the name in every duplicate using both approaches:

Sub Main()
    Dim JsonStr = "... the json string ..."     

    Dim o As JObject = JObject.Parse(JsonStr)
    Dim results = o("result")
    For Each resultProperty In results.Value(Of JObject)()
        'Only get properties like "1" inside the root "result" property
        If Not Integer.TryParse(resultProperty.Key, Nothing) Then Continue For

        'Approach 1: Manually Iterate over the duplicates array inside each result
        Dim duplicatesArray = resultProperty.Value("listing")("duplicates").Value(Of JArray)()
        For Each duplicate In duplicatesArray
            'Make sure there is a fornavn property
            If duplicate("fornavn") Is Nothing Then Continue For
            Console.WriteLine(duplicate("fornavn"))
        Next

        'Approach 2: Deserialize the listing into a .Net object
        Dim serializer As JsonSerializer = New JsonSerializer()
        Dim resultObject As Result = JsonConvert.DeserializeObject(Of Result)(resultProperty.Value.ToString())
        For Each duplicateObject In resultObject.listing.duplicates
            Console.WriteLine(duplicateObject.fornavn)
        Next
    Next

    Console.ReadKey()
End Sub

Class Result
    Property listing As Listing
End Class

Class Listing
    Property table As String
    Property id As String
    Property duplicates As Duplicate()
End Class

Class Duplicate
    Property table As String
    Property id As String
    Property idlinje As String
    Property fornavn As String
    'Continues with all the other properties...
End Class

Please note I just quickly wrote this code, so you might need to adjust it if some properties are not always present in the json response.

Community
  • 1
  • 1
Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112
  • You are correct when you say that the results and duplicates can be more then 1 hit. It can be from 0 to more than 10 really. – Martin Aug 05 '14 at 12:10
  • and i got results With the first approach, but needs to verify if there are more results and duplicates than 1. how is the easiest method in doing so? Also i have tried to look into the deserialize, but its looking pretty confusing to me at the moment. I created the classes, but have no clue how to use them. i can add them if needed, but the string i got when creating them is pretty long. – Martin Aug 05 '14 at 12:12
  • Thank you very much for writing all that code for me. I have look ed at it and will try approach 2 to begin With. I see that the code itself Works very well! :) Again thank you for taking the time to help me in this matter! – Martin Aug 06 '14 at 06:49