hi, i am receieving a repsonse from googles json api that has the formatted_address but i want to extract the city and county from either the formatted_address which is displayed in a label (lblAddress.text) or the JSON file Google gave me.

so for example: Palgrove Road, Pennywell, Sunderland, Tyne and Wear, SR4 8DX, UK.
Street/Village/Town/County/Postcode/Country.(This isn't how google columns the data but is how the formatted address displays and how we piece together an address locally)

so i would like to take Sunderland from that label and insert it into a textbox (txtTown.text) and also Tyne and Wear and put that in a text box too (txtCounty.text). these results differ always so the town could be Middlesbrough and the County could be County Durham etc.

the JSON results are
http://maps.googleapis.com/maps/api/geocode/json?address=palgroveroad%20sr48dx

can someone please try and help me or give me an example code that would be very much apprecated. Thanks

This is how i call in the JSON and extract the "formatted_address"

Dim request As HttpWebRequest = Nothing
        Dim response As HttpWebResponse = Nothing
        Dim reader As StreamReader = Nothing
        Dim json As String = Nothing
        Dim chars() As Char = txtFirstLine.Text
        For Each c As Char In chars
            If IsNumeric(c) Then
                Try
                    'Create the web request   
                    request = DirectCast(WebRequest.Create("http://maps.googleapis.com/maps/api/geocode/json?address=" + txtFirstLine.Text + txtPC.Text & "&sensor=false"), HttpWebRequest)
                    'Get response   
                    response = DirectCast(request.GetResponse(), HttpWebResponse)
                    'Get the response stream into a reader   
                    reader = New StreamReader(response.GetResponseStream())
                    json = reader.ReadToEnd()
                    response.Close()
                    TextBox1.Text = json
                    If json.Contains("ZERO_RESULTS") Then
                        lblAddress.Text = "No Address Available"
                    End If


                    If json.Contains("formatted_address") Then
                        'CurrentAddress.Text = "Address Available";
                        Dim start As Integer = json.IndexOf("formatted_address")
                        Dim [end] As Integer = json.IndexOf(", UK")
                        Dim AddStart As String = json.Substring(start + 21)
                        Dim EndStart As String = json.Substring([end])
                        Dim FinalAddress As String = AddStart.Replace(EndStart, "")
                        'Gives Full Address, One Line

                        lblAddress.Text = FinalAddress
                    End If
                Catch ex As Exception
                    Dim Message As String = "Error: " & ex.ToString()
                Finally
                    If (response IsNot Nothing) Then
                        response.Close()
                    End If
                End Try
                Return json

Edited 2 Years Ago by cbutler7: mistake

Have you tried parsing the JSON into an object structurte? here is a JSON string from a DropBox list files Query:

{"hash": "2e50103f8605f7639f7da0fd2e934fe4", "thumb_exists": false, "bytes": 0, "path": "/", "is_dir": true, "icon": "folder", "root": "app_folder", "contents": [{"rev": "5929d57df1", "thumb_exists": true, "path": "/flower.jpg", "is_dir": false, "client_mtime": "Mon, 15 Sep 2014 19:20:02 +0000", "icon": "page_white_picture", "bytes": 879395, "modified": "Mon, 15 Sep 2014 19:20:01 +0000", "size": "858.8 KB", "root": "app_folder", "mime_type": "image/jpeg", "revision": 89}, {"rev": "829d57df1", "thumb_exists": false, "path": "/test.xlsx", "is_dir": false, "client_mtime": "Mon, 08 Sep 2014 12:50:47 +0000", "icon": "page_white_excel", "bytes": 21699, "modified": "Mon, 08 Sep 2014 12:50:47 +0000", "size": "21.2 KB", "root": "app_folder", "mime_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "revision": 8}], "size": "0 bytes"}

A bit of a mess like this. However once you've determind the structure you can create an object structure like this

 Public Class dbFiles

        Private _contents As List(Of dbFile)
        Public Property contents As List(Of dbFile)
            Get
                Return _contents
            End Get
            Set(value As List(Of dbFile))
                _contents = value
            End Set
        End Property

        Private _hash As String
        Public Property hash As String
            Get
                Return _hash
            End Get
            Set(value As String)
                _hash = value
            End Set
        End Property

        Private _thumb_exists As Boolean
        Public Property thumb_exists As Boolean
            Get
                Return _thumb_exists
            End Get
            Set(value As Boolean)
                _thumb_exists = value
            End Set
        End Property

        Private _bytes As Long
        Public Property bytes As Long
            Get
                Return _bytes
            End Get
            Set(value As Long)
                _bytes = value
            End Set
        End Property

        Private _is_dir As Boolean
        Public Property is_dir As Boolean
            Get
                Return _is_dir
            End Get
            Set(value As Boolean)
                _is_dir = value
            End Set
        End Property

        Private _icon As String
        Public Property icon As String
            Get
                Return _icon
            End Get
            Set(value As String)
                _icon = value
            End Set
        End Property

        Private _root As String
        Public Property root As String
            Get
                Return _root
            End Get
            Set(value As String)
                _root = value
            End Set
        End Property

        Private _size As String
        Public Property size As String
            Get
                Return _size
            End Get
            Set(value As String)
                _size = value
            End Set
        End Property

    End Class

Once you matched the structure you serialize the jason into the structure:

eg

Dim MyFiles as dbFiles = GetJSON()

which get's your JSON string and serializes it into your object

        Public Function GetJSON() As dbFiles

            Dim uri As Uri = New Uri(Blah Blah Blah)
            Dim json As String = GetResponse(uri)

            Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()

            Return serializer.Deserialize(Of dbFiles)(json)

        End Function

You can then access each of the properties as you would normally.

MyFiles.IsDir

etc

Edited 2 Years Ago by J.C. SolvoTerra

Though instead of typing out all those properties like that just for a couple of bits of data you may just want to structure your properties like this

Public Property bytes As Long
Public Property is_dir As Boolean

etc

Note The property name and the object structure has to match the JSON names and structure.

No I havent. Thanks, will try and make sense of this and give it go! Will this work even though the property name is displayed after the information I am after?

Ie: <tag> "Sunderland"
<propname> "Town"

Because that's how the JSON is displaying the requested data

Looking at your provided JSON string it looks like the property name is long_name >"long_name" : "Sunderland"

for example, if you set your structure up correctly you would access it by the following

Dim Town as string = results.address_components(1).long_name

If you have trouble with this I will be happy to provide you with further assistance.

to get you started you would begin with the follwoing structure

Your base class may look something like this:

Private class MyResults
    Public results As List(Of Results)
    Public status As String
End Class

Private Class Results

    Public address_components As List(Of AddressComponents)
    Public formatted_address As String
    Public geometry As objGemoetry

End Class

Your AddressComponent object may look like this:

Private Class AddressComponents
    Public long_name As String
    Public short_name As String
    Public types As List(Of String)
End Class

Do you see how you're building an object structure to match the structure of the JSON string. The geometry class would be a little more complicated, but the same principal.

Edited 2 Years Ago by J.C. SolvoTerra

Sorry, I'll try that again...

-------

Looking at your provided JSON string it looks like the property name is long_name >"long_name" : "Sunderland"

for example, if you set your structure up correctly you would access it by the following

Dim Town as string = MyResults.results(0).address_components(1).long_name

If you have trouble with this I will be happy to provide you with further assistance.

to get you started you would begin with the follwoing structure

Your base class may look something like this:

Private class MyResults
     Public Sub New()
        results = New List(Of Result)
    End Sub
    Public property results As List(Of Result)
    Public property status As String
End Class

Your Result class may look like this

Private Class Result
    Public Sub New()
        address_components = New List(Of AddressComponents)
        types = New List(Of String)
        geometry = New GeometryData
    End Sub
    Public property address_components As List(Of AddressComponents)
    Public property formatted_address As String
    Public property geometry As GemoetryData
    Public property partial_match As Boolean
    Public property types As List(Of String)
End Class

Your AddressComponents object may look like this:

Private Class AddressComponents
    Public Sub New()
        types = New List(Of String)
    End Sub
    Public property long_name As String
    Public property short_name As String
    Public property types As List(Of String)
End Class

Do you see how you're building an object structure to match the structure of the JSON string. The geometry class would be a little more complicated, but the same principal.

Edited 2 Years Ago by J.C. SolvoTerra

i thought i could figure it out by myself but i have failed miserably :( lol. can i bother you into asking for further assistance?

Thanks

Of course you can. Am I right in assuming that you've got a good idea of what's going on, you're just having difficulty in matching the structure? I'll keep my eyes on this thread and have a look into this whilst waiti9ng for your response.

Just out of interest, do you have your current effort available to post so I can also see if you're not to far away from your solution?

BAre with me, I'll have a play in the mean time.

I don't understand where I should call in the JSON do I keep my current function or integrate new call in code into the coding you have kindly created. Also when I try to code the end result I'm getting an error on MyResults.results(0)

Ok, the first part of the structure is ok, so here's the Geometry bit:

The Complete Code Is At The End

In geometry you have a few properties, let's make a simple textified version:

-bounds
--northeast
---lat
---lng
--southwest
---lat
---lng
-location
--lat
--lng
-location_type
-viewport
--northeast
---lat
---lng
--southwest
---lat
---lng

From the above structure you can see there are a couple of properties, some of which the structure is repeated. so the base structure for geometry would have the following properties

bounds
location
location_type
viewport

viewport and bounds have the same sub properties

northeast
southwest

and those sub properties, as well as location have sub properties

lat
lng

so create a LatLong Object

Public Class LatLong
    Public Property lat As String
    Public Property lng As String
End Class

New we'll create a Coords object for northeast, southwest

Public Class Coords
    Public Property northeast As LatLong
    Public Property southwest As LatLong
End Class

and the actual GeometryData object

Public Class GeometryData
    Public Property bounds As Coords
    Public Property location As LatLong
    Public Property location_type As String
    Public Property viewport As Coords
End Class

Object Structure

So your complete structure now looks like this

Public Class MyResults
    Public Sub New()
        results = New List(Of Result)
    End Sub
    Public Property results As List(Of Result)
    Public Property status As String
End Class

Public Class Result

    Public Sub New()
        address_components = New List(Of AddressComponents)
        types = New List(Of String)
        geometry = New GeometryData
    End Sub
    Public Property address_components As List(Of AddressComponents)
    Public Property formatted_address As String
    Public Property geometry As GeometryData
    Public Property partial_match As Boolean
    Public Property types As List(Of String)

End Class

Public Class AddressComponents
    Public Sub New()
        types = New List(Of String)
    End Sub
    Public Property long_name As String
    Public Property short_name As String
    Public Property types As List(Of String)
End Class

Public Class GeometryData
    Public Property bounds As Coords
    Public Property location As LatLong
    Public Property location_type As String
    Public Property viewport As Coords
End Class

Public Class Coords
    Public Property northeast As LatLong
    Public Property southwest As LatLong
End Class

Public Class LatLong
    Public Property lat As String
    Public Property lng As String
End Class

Possible Form Source

and your form code may look like this
NOTE: INCLUDE REFERENCE TO SYSTEM.WEB.EXTENSIONS

Imports System.Net
Imports System.IO

Public Class Form1

    Private Const GOOGLE_API = "http://maps.googleapis.com/maps/api/geocode/json?address="

    Private Function GetJSON(Criteria As String) As MyResults

        'Not completely neccassary
        Criteria = Criteria.Replace(" ", "%20")

        Dim request As HttpWebRequest = Nothing
        Dim response As HttpWebResponse = Nothing
        Dim reader As StreamReader = Nothing
        Dim json As String = Nothing

        request = DirectCast(WebRequest.Create(GOOGLE_API & Criteria), HttpWebRequest)
        response = DirectCast(request.GetResponse(), HttpWebResponse)
        reader = New StreamReader(response.GetResponseStream())
        json = reader.ReadToEnd()
        response.Close()

        'INCLUDE REFERENCE TO SYSTEM.WEB.EXTENSIONS
        Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
        Return serializer.Deserialize(Of MyResults)(json)

    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim mResults As MyResults = GetJSON("palgroveroad sr48dx")

        'As predicted your home town string is found like this
        MsgBox(mResults.results(0).address_components(1).long_name)

    End Sub

End Class

The message box, as predicted follows the object structure and displays your home town

3f5267ea9a6c666011624da1b122680d

And if we inspect the mResults object you can see it is populated with all the JASON data

9e8fae776e868090116fb39bbf6d4e02

Edited 2 Years Ago by J.C. SolvoTerra

If thae parsing fails, you wont have any results so trying to access MyResults.Results(0) will "result" in an error as a result object hasn't been added to the results list.

This question has already been answered. Start a new discussion instead.