Get JSON data that returns a URL through Java

3

I'm trying to get some specific data from an http request, this request returns data in json, here's an example:

{
    "Head" : {
        "RequestArguments" : {
            "DataCollection" : "",
            "Scope" : "System"
        },
        "Status" : {
            "Code" : 0,
            "Reason" : "",
            "UserMessage" : ""
        },
        "Timestamp" : "2016-06-20T08:15:41+02:00"
    },
    "Body" : {
        "Data" : {
            "PAC" : {
                "Unit" : "W",
                "Values" : {
                    "1" : 49
                }
            },
            "DAY_ENERGY" : {
                "Unit" : "Wh",
                "Values" : {
                    "1" : 56
                }
            },
            "YEAR_ENERGY" : {
                "Unit" : "Wh",
                "Values" : {
                    "1" : 771939
                }
            },
            "TOTAL_ENERGY" : {
                "Unit" : "Wh",
                "Values" : {
                    "1" : 3246052
                }
            }
        }
    }
}

I am trying to get the numerical values of PAC, DAY_ENERGY, YEAR_ENERGY and TOTAL_ENERGY in the following way:

URL url3 = new URL("http://u020556.bi.ehu.es/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System");

try (InputStream is = url3.openStream();
     JsonReader rdr = Json.createReader(is)) {

    JsonObject obj = rdr.readObject();

    JsonObject body = obj.getJsonObject("Body");
    JsonObject data = body.getJsonObject("TOTAL_ENERGY");
    JsonObject values = data.getJsonObject("1");
    System.out.print(values.getString("1"));   
}

But the only thing I get is null . Could someone help me out?

    
asked by Cabasu 20.06.2016 в 08:30
source

2 answers

0

In the end I have achieved it in the following way:

          try (InputStream is = url3.openStream();
               JsonReader rdr = Json.createReader(is)) {

              JsonObject obj = rdr.readObject();

              JsonObject body = obj.getJsonObject("Body");
              JsonObject data = body.getJsonObject("Data");
              JsonObject energy = data.getJsonObject("TOTAL_ENERGY");
              JsonObject values = energy.getJsonObject("Values");
              System.out.println(values.getInt("1"));
          }
    
answered by 06.07.2016 / 11:30
source
0

Having a JSON multi level it is necessary to go through the object to read the data:

//Primero leemos el Body
JSONObject parent = (JSONObject) lev1.get("Body");

//A partir de aquí vamos bajando de nivel
JSONArray child1 = (JSONArray) parent.get("Data")

//Ya estamos en el nivel que necesitamos -- obtenemos TOTAL_ENERGY    
JsonObject data = child1.getJsonObject("TOTAL_ENERGY");

The other fields are trivial and you already agree well with their values.

    
answered by 20.06.2016 в 11:12