samtou006
samtou006

Reputation: 5

How to recover values from JsonObject java

I have a list of JSonObject, I want recover just the values of tow variables in json.

In java 8 I don't find the function getJSONObject,may be it's not recognized.. First of all I added my json to a list of JSONObject. But when I want get it, the editor Intellij propose just the function get.

Exemple: records.get(0).get("id") I got the result bellow, but when I want recover the varible inside like: records.get(0).get("id").get("875488")... I got an error.

My code:


JSONArray JSONArray = (JSONArray) obj;
List<JSONObject> records = new ArrayList<JSONObject>(); 

    for (int i=0; i<JSONArray.size(); i++) {

        records.add( (JSONObject) JSONArray.get(i) );

    }

I tried to recover the first tow value of "lat" and "lon" but I can't arrived. Someone can help me please ?

I want like as result:

lat = 12.13

lon =  5.02

Thank you.

Upvotes: 0

Views: 84

Answers (1)

LppEdd
LppEdd

Reputation: 21134

First off all, the correct Maven/Gradle dependency for JAVA-json is

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

If the method JSONObject#getJSONObject cannot be found, you're doing something wrong.


For the code part, that should do it. Adapt to your necessities.

final JSONArray jsonArray = new JSONArray(source);
final int length = jsonArray.length();

for (int i = 0; i < length; i++) {
    final JSONObject jsonObject = jsonArray.getJSONObject(i);
    final JSONObject forecastOrig =
            jsonObject.getJSONObject("875488")
                      .getJSONObject("forecast_orig");

    final double lon = forecastOrig.getDouble("lon");
    final double lat = forecastOrig.getDouble("lat");

    System.out.println(lon);
    System.out.println(lat);
}

Upvotes: 4

Related Questions