Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java & JSON Objects

Options
  • 08-10-2017 8:41pm
    #1
    Registered Users Posts: 4,567 ✭✭✭


    Hi,

    I'm trying to do a simple enough project around the JC Decaux Dublin Bikes api and using Java specifically but I am having quite a few issues around JSON manipulation. I'll post up my code and what I want it to do. Basically what I want to do is access the URL, retrieve the data and start accessing parts of the JSON data. eg. Stations, Addresses Any help most welcome.
    import java.net.*;
    import java.io.*;
    import java.util.Scanner;
    import org.json.JSONObject;
    
    public class AccessUrl {
        public static void main(String[] args) throws Exception {
    
        	String root = "https://api.jcdecaux.com/vls/v1/stations?contract="; //base url
            String city = "Dublin"; //enter city here
            String apiKey = "&apiKey=my api key goes here"; //secure key		
        	URL api = new URL(root + city + apiKey);
            
            BufferedReader in = new BufferedReader(
            new InputStreamReader(api.openStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine); 
            in.close();
            
            String out = new Scanner(api.openStream(), "UTF-8").useDelimiter("\\A").next();
            System.out.println("My JSON Data = " + out);
    

    That will print out what to me looks like JSON Data
    [{"number":42,"name":"SMITHFIELD NORTH","address":"Smithfield North","position":{"lat":53.349562,"lng":-6.278198},
    

    Now what I wanted to do next is basically retrieve select bits of this data so this is what I'm trying
    JSONObject station = new JSONObject(out.trim());
            String smithfield = (String) station.get("name");
            System.out.println("smithfield " + smithfield );
    

    I want that to essentially print Smithfield North but I'm getting an exception

    "A JSONObject text must begin with '{' at 1"


Comments

  • Registered Users Posts: 10,475 ✭✭✭✭28064212


    JSON Object
    {...}
    
    JSON Array
    [...]
    

    Boardsie Enhancement Suite - a browser extension to make using Boards on desktop a better experience (includes full-width display, keyboard shortcuts, dark mode, and more). Now available through your browser's extension store.

    Firefox: https://addons.mozilla.org/addon/boardsie-enhancement-suite/

    Chrome/Edge/Opera: https://chromewebstore.google.com/detail/boardsie-enhancement-suit/bbgnmnfagihoohjkofdnofcfmkpdmmce



  • Registered Users Posts: 4,567 ✭✭✭delta_bravo


    28064212 wrote: »
    JSON Object
    {...}
    
    JSON Array
    [...]
    

    Ok thanks for that. That is one area I did have confusion over. So I'd need to create an array object to store my data and then access the individual objects of the array.


  • Registered Users Posts: 6,250 ✭✭✭Buford T Justice


    Ok thanks for that. That is one area I did have confusion over. So I'd need to create an array object to store my data and then access the individual objects of the array.

    If the api is returning valid json (highly likely), it'll be returning either a single object
    {..}
    
    or an array of objects
    [{...},{...}]
    

    This will determine how you deal with the data you have.
    If its an array, you need to iterate through it and extract the objects you want. If its a singleton then you need to convert it into the object you want.


  • Registered Users Posts: 4,567 ✭✭✭delta_bravo


    Thanks for everyones help. I have made progress in extracting the elements of the array such as station name but I'm just wondering how would I further filter it down to say take the station name of the 3rd element of the array.

    I have a snip of what the json looks like and the code I have so far. It currently is printing all of the station names and ids but I just want to narrow it down more.
    URL urlBike = new URL(root + city + apiKey);
        	JSONTokener tokenerz = new JSONTokener(urlBike.openStream());
        	JSONArray objz = new JSONArray(tokenerz);
    
        	
        	for (int i = 0; i < objz.length(); ++i) {
        	    JSONObject bikeobj = objz.getJSONObject(i);
        	    int id = bikeobj.getInt("number");
        	    System.out.println("id " + id);
        	    String loc = bikeobj.getString("name");
        	    System.out.println("loc " + loc);
        	    // ...
        	}
    


  • Advertisement
  • Registered Users Posts: 1,893 ✭✭✭rex-x


    Depends on what you are trying to do, if you just want the 3rd element name then:
    URL urlBike = new URL(root + city + apiKey);
        	JSONTokener tokenerz = new JSONTokener(urlBike.openStream());
        	JSONArray objz = new JSONArray(tokenerz);
    
        	
        	for (int i = 0; i < objz.length(); i++) {
        	    JSONObject bikeobj = objz.getJSONObject(i);
            if (i == 2) {
        	    int id = bikeobj.getInt("number");
        	    System.out.println("idid);
        	    String loc = bikeobj.getString("name");
        	    System.out.println("locloc);
               }
        	    // ...
        	}
    

    Or if you wanted to search by name:
    URL urlBike = new URL(root + city + apiKey);
        	JSONTokener tokenerz = new JSONTokener(urlBike.openStream());
        	JSONArray objz = new JSONArray(tokenerz);
    
        	
        	for (int i = 0; i < objz.length(); i++) {
        	    JSONObject bikeobj = objz.getJSONObject(i);
                String loc = bikeobj.getString("name");
            if (loc == "SMITHFIELD NORTH") {
        	    System.out.println("location is " + loc);
               }
            else {
                    System.out.println("Not found")
                   }
        	    // ...
        	}
    


  • Registered Users Posts: 4,567 ✭✭✭delta_bravo


    rex-x wrote: »
    Depends on what you are trying to do....

    Thanks for the reply, really appreciate it


  • Registered Users Posts: 1,893 ✭✭✭rex-x


    I'm not sure why the code keeps getting messed up in the tags. Its well formatted when posted and then goes to crap but if I try and edit it then its perfect in the editor :confused: but you get the idea....
    Its not very useful in that form clearly but can be expanded on


  • Registered Users Posts: 4,567 ✭✭✭delta_bravo


    rex-x wrote: »
    I'm not sure why the code keeps getting messed up in the tags. Its well formatted when posted and then goes to crap but you get the idea....
    Its not very useful in that form clearly but can be expanded on

    Yeah the overall aim is to use the data for a site or data analysis but I just wanted to get to grips with the Java json basics first before I went for anything more ambitious. Thanks again


  • Registered Users Posts: 6,250 ✭✭✭Buford T Justice


    If its just the third element you want access to then you can reference it directly, though not necessarily best practice
        	URL urlBike = new URL(root + city + apiKey);
        	JSONTokener tokenerz = new JSONTokener(urlBike.openStream());
        	JSONArray objz = new JSONArray(tokenerz);
    
        	    JSONObject bikeobj = objz.getJSONObject(2);
        	    int id = bikeobj.getInt("number");
        	    System.out.println("id " + id);
        	    String loc = bikeobj.getString("name");
        	    System.out.println("loc " + loc);
        	    //
    


  • Advertisement
  • Registered Users Posts: 2,089 ✭✭✭henryporter


    Would it not be handier to use a JSON handler like Jackson or Gson: https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.2


  • Moderators, Technology & Internet Moderators Posts: 1,334 Mod ✭✭✭✭croo


    Would it not be handier to use a JSON handler like Jackson or Gson: https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.2
    Was just going to say I recently did a small Spring REST project and it used jackson


  • Registered Users Posts: 772 ✭✭✭maki


    Would it not be handier to use a JSON handler like Jackson or Gson: https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.2

    JsonPath seems like it would suit even better in this case when nested nodes are needed, rather than iterating over Jackson JsonNode objects:

    https://github.com/json-path/JsonPath


Advertisement