简体   繁体   中英

How to read JSON Object on the second array with Java/JavaFX code

I am trying to read JSON data with Java, I was successfully to read the first array, below is my JSON report from url.

{
  "success":1,
  "object":"sale",
  "id":"sl987575",
  "created":"2019-08-03 21:40:35",
  "product_id":"prd00123",
  "product_name":"AirBuss",
  "amount":"100.00",
  "currency":"USD",
  "status":"Completed",
  "meta":[],
  "customer":{
               "object":"customer",
               "id":"001234",
               "email":"someone@email.com",
               "name":"Full Name",
               "country":null,
               "firstname":"Full",
               "lastname":"Name"}}

I can read "product_name" and "status" but cannot read the "email" data.

    public static void call_me() throws Exception {
        String url = "Link WEbsite/api/?apiKey=23459876";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");
        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        //print in String
        System.out.println(response.toString());
        //Read JSON response and print
        JSONObject myResponse = new JSONObject(response.toString());
        System.out.println("result after Reading JSON Response");
        System.out.println("Product Name : "+myResponse.getString("product_id"));
        System.out.println("status : "+myResponse.getString("status"));
        System.out.println("Email : "+myResponse.getString("email"));
    }

Try this:

System.out.println("Email : " + myResponse.getJSONObject("customer").getString("email"));

Because 'email', 'country' etc. fields in a nested object named customer .

I just found solution for my own question..

JSONObject customer_data = myResponse.getJSONObject("customer");
System.out.println("Email : "+customer_data.getString("email"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM