Parsing Result

214 views
Skip to first unread message

Akintayo Olusegun

unread,
Oct 24, 2013, 2:21:00 PM10/24/13
to codenameone...@googlegroups.com

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "217",
               "short_name" : "217",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "East 21st Street",
               "short_name" : "E 21st St",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Midtown",
               "short_name" : "Midtown",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Manhattan",
               "short_name" : "Manhattan",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "New York",
               "short_name" : "New York",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "New York",
               "short_name" : "New York",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "New York",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "10010",
               "short_name" : "10010",
               "types" : [ "postal_code" ]
            }
         ],
         .....................
     },
      ..................
   ]
}

From the code above I want to get the political in the neighborhood, I did this "results[0]/address_components[0]/types[1]" But I am getting an error.

java.lang.IllegalArgumentException: Syntax error: array close must be followed by a separator

Please how do I get that value.

Thanks

Shai Almog

unread,
Oct 24, 2013, 3:02:42 PM10/24/13
to codenameone...@googlegroups.com
I'm guessing here without Eric but maybe add a / at the end?

Gareth Murfin

unread,
Oct 24, 2013, 10:44:03 PM10/24/13
to codenameone...@googlegroups.com
If you paste the code I will have a look too..

Akintayo Olusegun

unread,
Oct 25, 2013, 1:12:19 AM10/25/13
to codenameone...@googlegroups.com
Hi Shai, 

When I did that, I got 

java.lang.StringIndexOutOfBoundsException: String index out of range: 42

Akintayo Olusegun

unread,
Oct 25, 2013, 1:13:08 AM10/25/13
to codenameone...@googlegroups.com
Hi Gareth,

I am trying to parse the google geocode api.

Shai Almog

unread,
Oct 25, 2013, 1:56:06 AM10/25/13
to codenameone...@googlegroups.com
I'm afraid only Eric would know why that is behaving in this way.

Eric Coolman

unread,
Oct 25, 2013, 9:34:14 AM10/25/13
to codenameone...@googlegroups.com
Hi, that's another bug. Someone had reported it in the forums a while back and I forgot.  I'll look into producing a patch when I get home this eve, but in the meantime you could use the following as a workaround:

String types[] = result.getAsStringArray("results[0]/address_components[0]/types");

Eric

Gareth Murfin

unread,
Oct 25, 2013, 6:00:28 PM10/25/13
to codenameone...@googlegroups.com
this is all news to me (this amazing ability to do "results[0]/address_components[0]/types[1]" or the likes, I went through HELL and HIGH WATER.. writing this (and I swear CN1 has EXTREMELY POOR parsing, unless ive done something drastically wrong - hopefully our new google lib will help lol???)..

This took 9 hours of PAIN.. I post this hear because this sort of example code is SERIOUSLY LACKING, not only in CN1 but even J2SE.. Enjoy.


 private void GETCOORDS(){//final Dialog progress) {
        _("GETCOORDS");
        try {
            
            ConnectionRequest req = new ConnectionRequest() 
            {
                protected void readResponse(InputStream input) throws IOException 
                {
                    JSONParser p = new JSONParser();
                    Hashtable h = p.parse(new InputStreamReader(input));
                    // "status" : "REQUEST_DENIED"
                    String response = (String)h.get("status");
                    _("//////////////STATUS FROM API: "+response);
                    if(response.equals("REQUEST_DENIED"))
                    {
                       _("Request Denied "+(String)h.get("error_message"));//obtain a key!
                       return;
                    }
                                            
                    //PARSE the json of directions data from google, warning this is hideous CN1 has very bad parsing
                    //
                    RouteHolder routeHolder = new RouteHolder();
                    //routeholder
                    //  + LEGS
                    //    + STEPS
                                        
                    final Vector vec = (Vector) h.get("routes");
                    _("///////////////////////vec size:"+vec.size());
                    
                    Leg mylegs[] ;//= new Leg[vec.size()];
                    
                    for (int i = 0; i < vec.size(); i++) {
                        
                        Hashtable entry = (Hashtable)vec.elementAt(i);
                        
                        String copyrights = (String) entry.get("copyrights");
                        _("copyrights:"+copyrights);
                        routeHolder.copyrights=copyrights;
                        
                        
                         String summary = (String) entry.get("summary");
                        _("summary:"+summary);
                        routeHolder.summary=summary;
                        
                        //////////////////////////////////////////////////////////
                        //GET THE LEGS OF THE JOURNEY/////////////////////////////
                        /////////////////////////////////////////////////////////
                        
                        
                        Vector legs = (Vector) entry.get("legs");
                        
                        mylegs = new Leg[ legs.size() ];
                        
                        //_("legs:"+legs);
                        for (int j=0; j<legs.size(); j++)
                        {
                            Hashtable distance = (Hashtable) legs.get(j);
                           
                             mylegs[j]=new Leg();
                            
                            //each step has a number of things it can hold..
                           
                            _("________________________________________________________");
                            //DISTANCE////////////////
                            _("DISTANCE:");
                            Hashtable distanceHT = (Hashtable) distance.get("distance");
                             
                            String textDistance= (String)distanceHT.get("text");
                            _("text:"+textDistance);
                            Double valueDistance= (Double)distanceHT.get("value");
                            _("value:"+valueDistance);
                                                 
                            Distance dist = new Distance(textDistance,valueDistance);
                            mylegs[j].distance = dist;
                            //////////////////////////
                            
                            //DURATION////////////////
                            _("DURATION");
                            Hashtable durationHT = (Hashtable) distance.get("duration");
                            
                            String textDuration= (String)durationHT.get("text");
                            _("text:"+textDuration);
                            Double valueDuration= (Double)durationHT.get("value");
                            _("value:"+valueDuration);
                                                        
                            Duration dura = new Duration(textDuration,valueDuration);
                            mylegs[j].duration = dura;
                            ///////////////////////////
                            
                            //END LOCATION/////////////
                            _("#### end_location:");
                            Hashtable end_location = (Hashtable) distance.get("end_location");
                            Double lat = (Double) end_location.get("lat");
                            _("########lat :"+lat);
                            Double lng = (Double) end_location.get("lng");
                            _("########lng:"+lng);
                            
                            Coord endLocationCoord = new Coord(lng,lat);
                            mylegs[j].endLocationCoord=endLocationCoord;
                            ///////////////////////////
                            
                                                       
                            ///START LOCATION////////////////////
                            _("#### start_location:");
                            Hashtable start_location = (Hashtable) distance.get("start_location");
                            lat = (Double) start_location.get("lat");
                            _("########lat :"+lat);
                            lng = (Double) start_location.get("lng");
                            _("########lng:"+lng);
                            
                            Coord startLocationCoord = new Coord(lng,lat);
                            mylegs[j].startLocationCoord=startLocationCoord;
                            /////////////////////////////////////
                            
                            ///END ADDRESS////////////////////////////
                            String end_address = (String) distance.get("end_address");
                            _("END ADDRESS:"+end_address);
                            
                            mylegs[j].end_address= end_address;
                            //////////////////////////////////////////
                            
                            
                            ///START ADDRESS///////////////////////////
                            String start_address = (String) distance.get("start_address");
                            _("START ADDRESS:"+start_address);
                            
                            mylegs[j].start_address= start_address;
                            //////////////////////////////////////////
                            
                            
                            
                            //VIA WAYPOINTS////////////////////////////
                            _("#### via_waypoint:");
                            Vector via_waypoint = (Vector) distance.get("via_waypoint");
                            /// implement this when needed!
                            /////////////////////////////////////
                            
                            
                            Vector steps = (Vector) distance.get("steps");
                            _("STEPS:"+steps.size());
                            
                            Step mysteps[] = new Step[steps.size()];
                            
                            
                            ///////////////////////////////////////////////////////////////
                            ////////////////////GET EACH STEP SEPERATELY///////////////////
                            ///////////////////////////////////////////////////////////////
                            for (int m=0; m<steps.size(); m++)
                            {
                                
                                
                                 mysteps[m]=new Step();
                                
                                Hashtable stepsHT = (Hashtable) steps.get(m);
                                // _("steps:"+stepsHT.size());
                                 
                                //_("_________________________________________________________");
                                //_("#### Distance:");
                                Hashtable distanceHT2 = (Hashtable) stepsHT.get("distance");
                                String text = (String) distanceHT2.get("text");
                                //_("########text :"+text);
                                Double value = (Double) distanceHT2.get("value");
                                //_("########value:"+value);
                                
                                
                                dist = new Distance(text,value);
                                mysteps[m].distance = dist;
                                
                                
                                //_("#### Duration:");
                                Hashtable durationHT2 = (Hashtable) stepsHT.get("duration");
                                text = (String) durationHT2.get("text");
                                //_("########text :"+text);
                                Double valueDbl = (Double) durationHT2.get("value");
                                //_("########value:"+valueDbl);
                                
                                dura = new Duration(text,valueDbl);
                                mysteps[m].duration = dura;
                                
                                
                                //_("#### end_location:");
                                end_location = (Hashtable) stepsHT.get("end_location");
                                lat = (Double) end_location.get("lat");
                                //_("########lat :"+lat);
                                lng = (Double) end_location.get("lng");
                                //_("########lng:"+lng);
                                
                                endLocationCoord = new Coord(lng,lat);
                                mysteps[m].endLocationCoord=endLocationCoord;
                                
                                String html_instructions = (String) stepsHT.get("html_instructions");
                                //_("####html_instructions:"+html_instructions);
                                
                                //_("####start_location:");
                                start_location = (Hashtable) stepsHT.get("start_location");
                                lat = (Double) start_location.get("lat");
                                //_("########lat :"+text);
                                lng = (Double) start_location.get("lng");
                                //_("########lng:"+value);
                                
                                startLocationCoord = new Coord(lng,lat); 
                                mysteps[m].startLocationCoord=endLocationCoord;
                                
                                String travel_mode = (String) stepsHT.get("travel_mode");
                                //_("####travel_mode:"+travel_mode);
                                
                                mysteps[m].travel_mode=travel_mode;
                                
                                html_instructions = (String) stepsHT.get("html_instructions");
                                //_("####html_instructions:"+html_instructions);
                                mysteps[m].html_instructions=html_instructions;
                                
                                
                                //_("####Polyline:");
                                Hashtable polyline = (Hashtable) stepsHT.get("polyline");
                                text = (String) polyline.get("points");
                                //_("########points :"+text);
                                
                                 mysteps[m].points=text;
                                
                                 String maneuver = (String) stepsHT.get("maneuver");
                                //_("####maneuver:"+maneuver);
                                
                                 mysteps[m].maneuver=maneuver;
                                
                                 
                                
                                
                                 
                            }
                            
                             mylegs[j].steps= mysteps;
                            ///////////////////////////////////////////////////////////////////
                           
                             
                            
                            
                            
                        }
                        routeHolder.mylegs=mylegs;
                        
                        
                        
                        
                        _("____________________________");
                        _("##### PARSING COMPLETE #####");
                        _("____________________________");
                        _("testing data");
                        _("routeHolder copyright:"+routeHolder.copyrights);
                        _("routeHolder #legs:"+routeHolder.mylegs.length);
                        for (int x=0; x<routeHolder.mylegs.length; x++)
                        {
                            Leg leg = routeHolder.mylegs[x];
                            _("  "+x+"// Leg contains "+leg.steps.length+" steps");// ---> start_address:"+leg.start_address);
                            _("  Leg is "+leg.distance.text+" which will take "+leg.duration.text);
                            _("  Start @ "+leg.start_address);
                            _("  End   @ "+leg.end_address);
                            
                            if(segmentsToPlotSTART==null)
                            {
                                segmentsToPlotSTART= new Coord[leg.steps.length];
                            }
                            
                            for (int y=0; y<leg.steps.length; y++)
                            {
                                Step step = leg.steps[y];
                                _("    "+y+"// START Step distance is "+step.distance.text+" "+step.html_instructions);
                                
                                segmentsToPlotSTART[y] = step.startLocationCoord;
                            }
                            
                            if(segmentsToPlotEND==null)
                            {
                                segmentsToPlotEND= new Coord[leg.steps.length];
                            }
                            
                            for (int y=0; y<leg.steps.length; y++)
                            {
                                Step step = leg.steps[y];
                                _("    "+y+"// END Step distance is "+step.distance.text+" "+step.html_instructions);
                                
                                segmentsToPlotEND[y] = step.endLocationCoord;
                            }
                        }
                   
                    }
                }
            };
            
               String origin = ""+lastLocation.getLatitude()+","+lastLocation.getLongitude();
         String dest   = closestStation.latitude+","+closestStation.longitude;
         
            
            req.setPost(false);
            //req.addArgument("location", "" + loc.getLatitude() + "," + loc.getLongtitude());
            req.addArgument("origin", origin);
            req.addArgument("destination", dest);
            req.addArgument("sensor", "false");
            // req.addArgument("client", "radiantsilverlabs");
            
            _("origin:"+origin);
            _("destination:"+dest);
            
            //get your own key from https://developers.google.com/maps/documentation/places/
            //and replace it here.
            String key = Prefs.GOOGLE_MAPS_KEY;//AddYourOwnKeyHere";
            
          //  req.addArgument("key", key);

            NetworkManager.getInstance().addToQueueAndWait(req);
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }


  


--
You received this message because you are subscribed to a topic in the Google Groups "CodenameOne Discussions" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/codenameone-discussions/NnVSd6KSj9o/unsubscribe.
To unsubscribe from this group and all its topics, send an email to codenameone-discu...@googlegroups.com.
Visit this group at http://groups.google.com/group/codenameone-discussions.
To view this discussion on the web visit https://groups.google.com/d/msgid/codenameone-discussions/a7fde0ac-8fbd-466b-a92a-61bde3f82fb3%40googlegroups.com.

For more options, visit https://groups.google.com/groups/opt_out.



--
Gareth Murfin
(Android Freelancer)

Eric Coolman

unread,
Oct 25, 2013, 9:14:46 PM10/25/13
to codenameone...@googlegroups.com
The Expression Language (EL) support in Codename One is similar to XPath/XSL if you're familiar with that.  It can be used to query JSON, XML, XHTML, nested hashtable/vector structures, and other structured documents (by implementing the com.codename1.processing.StructuredContent interface).  I blogged a bit about it here:

http://gadgets.coolman.ca/new-feature-introduction-expression-language-for-json-and-xml/

Eric
To unsubscribe from this group and all its topics, send an email to codenameone-discussions+unsub...@googlegroups.com.

Steve Hannah

unread,
Oct 25, 2013, 10:06:51 PM10/25/13
to codenameone...@googlegroups.com
On Fri, Oct 25, 2013 at 3:00 PM, Gareth Murfin <gareth...@gmail.com> wrote: 
 WATER.. writing this (and I swear CN1 has EXTREMELY POOR parsing, unless ive done something drastically wrong - hopefully our new google lib will help lol???)..

JSONParser is not the only way to parse JSON in CN1.   It is just extremely convenient because it is built in and the EL stuff is just quite powerful.  That said, you can you any JSON parsing library you like.    Two ways that I have used before are:

1. Using the Javascript bridge and using webkit to do the parsing (only valid for platforms with native browser components).  

2. Using an alternate Java JSON library.  E.g. I have used this parser before and it works fine.

Steve

Shai Almog

unread,
Oct 26, 2013, 3:19:12 AM10/26/13
to codenameone...@googlegroups.com
JavaSE has great parsing because of JaxB which won't be useful here since we don't have bytecode manipulation or reflection on the client.
Feel free to suggest improvements.

Eric Coolman

unread,
Oct 27, 2013, 2:49:00 AM10/27/13
to codenameone...@googlegroups.com
Akintayo:

I've filed a patch for the EL processing to resolve the issue you were seeing.  The path results[0]/address_
components[2]/types[1] will now return the second string in the array ("political").  If your index is out of range,
it will return null.  I don't believe this functionality will be useful, but at least it should now behave as expected.

I also added a powerful new "contains" operator (%) which will work against both arrays and single strings that I
believe will be more useful to you.  With your JSON fragment as an example, here is how to use the new
contains operator:

Select all postal codes (example returns: "10010"):

        result.getAsStringArray("//address_components[types % postal_code]/long_name")

Select the long names of all components with "political" types (example returns "Midtown", "Manhatten", "New York", "New York", "New York", "US"):

        result.getAsStringArray("//address_components[types % political]/long_name")

Select the long names of the neighborhood (example returns "Midtown", I believe this is what you were looking for):

        result.getAsStringArray("//address_components[types % (neighborhood, political)]/long_name")

Select the short name of admin level 1 address (example returns "NY"):

        result.getAsStringArray("//address_components[types % (administrative_area_level_1, political)]/short_name")

Match a string instead of an array - select the long name where the short name contains "21" (example returns "217" and "East 21st Street")

        result.getAsStringArray("//address_components[short_name % 21]/long_name")

Hope that helps.


Eric


On Thursday, October 24, 2013 2:21:00 PM UTC-4, Akintayo Olusegun wrote:

{

Akintayo Olusegun

unread,
Oct 28, 2013, 1:16:02 AM10/28/13
to codenameone...@googlegroups.com

@Eric AWESOME!!!


@Gareth, I have completed and tested the directions API and geocode/reverse geocode. 

Here is the github link. https://github.com/segun/coma 

It contains some great expression language usages.

Next up is the Places API.

I took a look at sprockets and I like the way you can chain parameters, but it this version of the API, you will have to specify the parameters yourself.


@Chen/@Shai

Does codename one support variable argument list?

Shai Almog

unread,
Oct 28, 2013, 2:28:36 AM10/28/13
to codenameone...@googlegroups.com
You mean varags for methods? Yes, its part of the Java 5 language features.
Reply all
Reply to author
Forward
0 new messages