Search code examples
javajsonparsingyql

parse json using java (simplejson)


I need to parse json which I get from YQL but I am having trouble as I am not getting the results I need. I am using simple json (https://code.google.com/p/json-simple/wiki/DecodingExamples) and trying to follow the documentation. The problem is the example they show are very limited (I am very new to json). I want to extract everything in the array (Sy, Date, O, H, L, C, and V ). In the documentation they show how to extarct elements from an array if the json object is just as an array, but I have an array + some extra stuff on top:

{"query"
        {"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"

This is the full json object, how would I extract just the array?

{"query"
    {"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
        {"array":[{"Sy":"Y","Date":"2010-03-10","O":"16.51","H":"16.94","L":"16.51","C":"16.79","V":"33088600"},
                  {"Sy":"Y","Date":"2010-03-09","O":"16.41","H":"16.72","L":"16.40","C":"16.53","V":"20755200"},
                  {"Sy":"Y","Date":"2010-03-08","O":"16.32","H":"16.61","L":"16.30","C":"16.52","V":"30554000"}
        ]}}}

Solution

  • i use https://code.google.com/p/org-json-java/downloads/list

    this is simple

    try{
            String json = "JSON source";
            JSONObject j = new JSONObject(json);
            JSONArray arr = j.getJSONObject("query").getJSONObject("results").getJSONArray("array");
            for(int i=0; i<arr.length(); i++){
                JSONObject obj = arr.getJSONObject(i);
                String sy = obj.getString("Sy");
                String date = obj.getString("Date");
                String o = obj.getString("O");
                String h = obj.getString("H");
                String l = obj.getString("L");
                String c = obj.getString("C");
                String v = obj.getString("V");
            }
        }
        catch(JSONException e){
    
        }