13

I want to parse a JSON file in java and get the following values from the file mentioned below:

{
  "status": "OK",
  "origin_addresses": [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
  "destination_addresses": [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
  "rows": [ {
    "elements": [ {
      "status": "OK",
      "duration": {
        "value": 340110,
        "text": "3 jours 22 heures"
      },
      "distance": {
        "value": 1734542,
        "text": "1 735 km"
      }
    }, {
      "status": "OK",
      "duration": {
        "value": 24487,
        "text": "6 heures 48 minutes"
      },
      "distance": {
        "value": 129324,
        "text": "129 km"
      }
    } ]
  }, {
    "elements": [ {
      "status": "OK",
      "duration": {
        "value": 288834,
        "text": "3 jours 8 heures"
      },
      "distance": {
        "value": 1489604,
        "text": "1 490 km"
      }
    }, {
      "status": "OK",
      "duration": {
        "value": 14388,
        "text": "4 heures 0 minutes"
      },
      "distance": {
        "value": 135822,
        "text": "136 km"
      }
    } ]
  } ]
}

From every element, i want to get the value field of both distance and duration. How do i do this?

Kaushik Balasubramanain
  • 1,248
  • 6
  • 28
  • 42
  • 1
    check this: http://stackoverflow.com/questions/2255220/how-to-parse-a-json-and-turn-its-values-into-an-array – aayoubi Jan 20 '12 at 09:33
  • The org.json library is great for simply parsing JSON. This video shows [how to parse JSON files using org.json.](https://www.youtube.com/watch?v=ZHuHc6oF1ec) Hope it helps. – drorw Nov 20 '18 at 06:12

7 Answers7

10

Using the json.org reference implementation (org.json homepage, Download here). The code is a bit messy but I think it does what you are asking for. You can take alot of shortcuts by not creating all this objects but to access them directly. The reason that I do it this way is an attempt to make it easier to follow whats happening.

package com.mypackage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Main {
    public static void main(String[] args) {
        String jsonStr = "{\"status\": \"OK\",\"origin_addresses\": [ \"Vancouver, BC, Canada\", \"Seattle, État de Washington, États-Unis\" ],\"destination_addresses\": [ \"San Francisco, Californie, États-Unis\", \"Victoria, BC, Canada\" ],\"rows\": [ {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 340110,\"text\": \"3 jours 22 heures\"},\"distance\": {\"value\": 1734542,\"text\": \"1 735 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 24487,\"text\": \"6 heures 48 minutes\"},\"distance\": {\"value\": 129324,\"text\": \"129 km\"}} ]}, {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 288834,\"text\": \"3 jours 8 heures\"},\"distance\": {\"value\": 1489604,\"text\": \"1 490 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 14388,\"text\": \"4 heures 0 minutes\"},\"distance\": {\"value\": 135822,\"text\": \"136 km\"}} ]} ]}";

        try {
            JSONObject rootObject = new JSONObject(jsonStr); // Parse the JSON to a JSONObject
            JSONArray rows = rootObject.getJSONArray("rows"); // Get all JSONArray rows

            for(int i=0; i < rows.length(); i++) { // Loop over each each row
                JSONObject row = rows.getJSONObject(i); // Get row object
                JSONArray elements = row.getJSONArray("elements"); // Get all elements for each row as an array

                for(int j=0; j < elements.length(); j++) { // Iterate each element in the elements array
                    JSONObject element =  elements.getJSONObject(j); // Get the element object
                    JSONObject duration = element.getJSONObject("duration"); // Get duration sub object
                    JSONObject distance = element.getJSONObject("distance"); // Get distance sub object

                    System.out.println("Duration: " + duration.getInt("value")); // Print int value
                    System.out.println("Distance: " + distance.getInt("value")); // Print int value
                }
            }
        } catch (JSONException e) {
            // JSON Parsing error
            e.printStackTrace();
        }
    }
}
jake stayman
  • 1,687
  • 13
  • 22
MrKiane
  • 4,803
  • 2
  • 17
  • 27
6
  1. Create an class structure that reflects the JSON
  2. Use a library like Jackson or GSON to deserialize the json to instances of your classes.

If you want a more dynamic approach, the above frameworks can also serialize to maps.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
1

Use a library for working with JSON. For example google-gson.

shift66
  • 11,760
  • 13
  • 50
  • 83
1

as Bozho said create class structure that reflacts JSON and then use jacson library as follow:

refer Parsing JSON File Java

ObjectMapper mapper = new ObjectMapper();
Projects projs =
mapper.readValue(new File("projects.json"),Projects.class);
ArrayList<Project> projects = projs.get("projects");
for (Project p : projects) {
ArrayList<String> description = p.getDescription();
for (String s : description) {
System.out.println(s);
Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
0

You can use :

org.bson.Document d = org.bson.Document.parse("{ foo: \"bar\" }");
lmo
  • 497
  • 5
  • 23
0

You can use a library like JSON-java

import org.json.JSONObject;

String jsonString = ...
JSONObject object = new JSONObject(jsonString);
String status = object.getString("status");
onof
  • 17,167
  • 7
  • 49
  • 85
-1

yes you can use jacson to parse it but there is more easy way to do it its Jsonme lib "import org.json.me" you dont have to add jar file to use it

     JSONObject obj = new JSONObject("{'var1':'val1','var2':200});
     String var1=obj.getString("var1");
     int var2=obj.getInt("var2");

yes its more easy but if your project is complex i advice you to use jacson lib

touti
  • 1,164
  • 6
  • 18