0

I'm looking to train myself in JSON (request, response and parsing).

I'm trying to develop a simple application, parsing the response into a list as seen in this app (never mind the language, just see the screenshots)

However, JSON and parsing it looks like magic to me right now and I currently got no idea on how to use it. I've programmed a lot of c#, but markup languages and respones with tons of brackets, etc just confuses me.

Here you can see code snippets from the place I'm trying to parse. I'm going to use this as a people search app. Really need to work on my parsing skills.

I'm not asking you to do it for me, just point me to some easy tutorials and things like that.

Java equivalent code snippet from the site showing me the API:

package com.eniro.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;

public class EniroAPIExample { 
    private static ObjectMapper objectMapper = new ObjectMapper (); 
    public static void main(String[] args) throws JsonParseException, JsonProcessingException,     IOException { 
    URL eniroApiUrl = new URL("http://api.eniro.com/cs/search/basic?profile=[profile]&key=                [key]&country=se" +
    "&version=1.1.3&search_word=pizza"); 

    HttpURLConnection eniroApiConn = (HttpURLConnection) eniroApiUrl.openConnection(); 

    if (eniroApiConn == null) { 
        return; 
    } 
    int respCode = eniroApiConn.getResponseCode(); 

    if (respCode != 200) { 
        return; 
    } 

    BufferedReader in = new BufferedReader(new InputStreamReader(eniroApiConn.getInputStream(),     "UTF-8")); 
    StringBuilder strResult = new StringBuilder(); 

    String inputLine; 
    while ((inputLine = in.readLine()) != null) { 
        strResult.append(inputLine); 
    } 
    in.close(); 
    JsonNode json =     objectMapper.readTree(objectMapper.getJsonFactory().createJsonParser(strResult.toString())); 
    System.out.println("Title: "+json.path("title")); 
} 
}

Edit:

I tried this code from this question:

    private void search(string input)
    {
        // Perform the search here
        Uri searchUri = new Uri("https://maps.googleapis.com/maps/api/geocode/json?address=1600%20Amphitheatre%20Parkway,%20Mountain%20View,%20CA&sensor=false");
        try
        {
            WebClient web;
            web = null;
            web = new WebClient(); web.DownloadStringAsync(searchUri); web.DownloadStringCompleted += web_DownloadStringCompleted;
        }
        catch (WebException)
        {
        }
    }

    public class People
    {
        public List<Person> data { get; set; }
    }

    public class Person
    {
        public string id { get; set; }
        public string name { get; set; }
        public string phonenumber { get; set; }
        public string address { get; set; }
    }

But I don't really know where to go from there. I looked at this library, but I ain't getting anywhere

All the best, Erik

Community
  • 1
  • 1
Erik
  • 799
  • 2
  • 15
  • 27

1 Answers1

0

I guess you are familiar with what the first lines of the presented code do. Until in.close(); it is basically accessing a URL and parsing the contents into a String.

In your Java code the line

    JsonNode json = objectMapper.readTree(objectMapper.getJsonFactory().createJsonParser(strResult.toString())); 

transforms the returned String into an accessible JSON-object. The docs for a Jackson JsonNode can be found here.

The last line

System.out.println("Title: "+json.path("title")); 

simply tries to access the field "title" in your JSON. This would for example be applicable if you had a JSON-string like:

{title: "Hairy Dotter", 
author: "D.K. Powding"}

For a better explanation I will use a different URL, which is accessible at: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false

So if you click on it you can see that we got some nice JSON here, still it is far more complex than the previous example! If you want to access the latitude of your provided address you would go like that:

json.path("results").get(0).path("geometry").path("location").path("lat");

I use the get(0) because results contains a JSON-array and I want to access the first object. The rest should be quite clear as I simply access the objects by their name.

Hint: If you want an easy-to-read representation of the JSON presented in the example, open your Chrome or Firefox developer console and paste the following code:

var x = {
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "1600",
               "short_name" : "1600",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Amphitheatre Parkway",
               "short_name" : "Amphitheatre Pkwy",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Mountain View",
               "short_name" : "Mountain View",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Kalifornien",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "USA",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "94043",
               "short_name" : "94043",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "1600 Amphitheatre Parkway, Mountain View, Kalifornien 94043, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.4219985,
               "lng" : -122.0839544
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.4233474802915,
                  "lng" : -122.0826054197085
               },
               "southwest" : {
                  "lat" : 37.4206495197085,
                  "lng" : -122.0853033802915
               }
            }
         },
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
};
console.log(x);

This should give you a really nice representation that you can easily click through and understand. I hope this helps you!

Edit: Everything enclosed in curly brackets is an object itself. E.g.:

{ "long_name" : "Amphitheatre Parkway", 
"short_name" : "Amphitheatre Pkwy", 
"types" : [ "route" ] }

is an object that has 3 sub-objects, which are stored as key-value pairs (long_name, short_name and types). See JSON Syntax for a quick overview. By the way: you can nest objects by as many levels as you want:

{"objectKey": {"innerObjectKey":{"mostInnerObjectkey":"mostInnerObjectValue"}}}

The value of types is an array. Here is an example of an array with multiple values in it:

{"fruits": ["apple", "banana", "strawberry"]}
snrlx
  • 4,987
  • 2
  • 27
  • 34
  • First, thanks A LOT for your extensive answer, I REALLY appreciate it! Second, I see you can get the items after it's "id". But the example you showed me; does it contain a list of items? is { "long_name" : "Amphitheatre Parkway", "short_name" : "Amphitheatre Pkwy", "types" : [ "route" ] }, an item alone? – Erik Feb 14 '14 at 14:43
  • If I wanted to populate the list with the data from your example, shall I really just cycle through the items one-by-one from results and adress components? – Erik Feb 14 '14 at 14:44
  • I edited my answer for a little more detailed explanation of JSON. However I didn't really get what you meant in your second comment. Just try around a little bit and if you run into any problems, just ask :) – snrlx Feb 14 '14 at 15:52
  • I think I'm starting to understand it. Say I created a ListBox in my app for windows phone 8 (C#), how would i then populate that list? Should I create a class for each item or modify an existing ListBoxItem? How would I go about this? – Erik Feb 14 '14 at 15:56
  • I guess looking into this post might help you: http://stackoverflow.com/questions/1732054/how-might-i-add-an-item-to-a-listbox – snrlx Feb 14 '14 at 16:00
  • I know how to add items like that to a ListBox - that's not the issue; however I need to plot the JSON parsed data into it. Is there a fancy way of doing just that or do you have to set up a for() loop for every object in the response? – Erik Feb 14 '14 at 16:10
  • Ok then how about this: http://stackoverflow.com/questions/7895105/json-deserialize-c-sharp This post explains you how to turn the JSON into a C# object, which you can then easily access. Just reproduce the structure of your JSON as C# objects and you should be fine :) – snrlx Feb 14 '14 at 16:18
  • Can I simply grab the "long_name" id's in your example and put them into a list, combining lists of all the id's (if your understand)? Or is that not going to work? – Erik Feb 14 '14 at 16:42