4

I'm currently learning some android programming with JAVA. My teacher shared this piece of code which will consume an API, get its JSON file, and convert it to a JSONArray file. Then he will Iterate through that JSONArray and put them into an ArrayList before displaying them onto an activity.

The problem is that the API that I'm consuming returns a JSONObject file instead, and I do not know how to properly convert this to JSONArray.

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONArray jObj = null;
StringBuilder sbParams;
String paramsString;

public JSONArray makeHttpRequest(String url, String method) {

    sbParams = new StringBuilder();

   if(method.equals("GET")){
        // request method is GET

        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        try {
            urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();

            conn.setDoOutput(false);

            conn.setRequestMethod("GET");


            conn.setRequestProperty("AccountKey", "pVU56+0hI26DNLeTzlU/Dw==");
            conn.setRequestProperty("UniqueUserId", "33c07f2f-b4c0-4151-acd3-e0829b303d2c");
            conn.setRequestProperty("accept", "application/json");

            conn.setConnectTimeout(15000);

            conn.connect();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    try {
        //Receive the response from the server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        Log.d("JSON Parser", "result: " + result.toString());

    } catch (IOException e) {
        // e.printStackTrace();
    }

    conn.disconnect();

    // try parse the string to a JSON object
    try {

        jObj = new JSONArray(result.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;
}

}

API URL and its custom headers:

URL: http://datamall2.mytransport.sg/ltaodataservice/TaxiAvailability

headers-

AccountKey: pVU56+0hI26DNLeTzlU/Dw==
UniqueUserId: 33c07f2f-b4c0-4151-acd3-e0829b303d2c
accept: application/json

EDIT2: I use this to get my raw data with custom headers. http://requestmaker.com/

EDIT: This is the JSON that I get.

{
  "odata.metadata": "http://datamall2.mytransport.sg/ltaodataservice/$metadata#TaxiAvailability",
  "value": [
    {
      "Longitude": 103.84009,
      "Latitude": 1.35989
    },
    {
      "Longitude": 103.84679,
      "Latitude": 1.35544
    },
    {
      "Longitude": 103.76928,
      "Latitude": 1.4419
    }
    ....
    ]
    }
3
  • Please post your JSON. Commented Feb 23, 2016 at 9:47
  • Edited with it. Check it out. Commented Feb 23, 2016 at 9:50
  • 3
    JSONObject json_obj = new JSONObject(json_string); JSONArray array = json_obj.getJSONArray("value") Commented Feb 23, 2016 at 9:53

2 Answers 2

9

Add this in place of jObj = new JSONArray(result.toString());

JSONObject obj = new JSONObject(result.toString());
JSONArray arr = obj.getJSONArray("value");

Now you can use JSONArray arr the way you want.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the quick help! So from what I can tell, the array starts after the value "opens" yes?
Yes correct. It will have all the groups (JSONObject) of latitude and longitude.
So should I create a local variable for arr? Because I can't use arr to parse it on the second try-catch because its declared in the first try-catch.
Simply put this code in second try-catch. I didn't notice you have two try-catch blocks. Edited my answer also.
What if there is no value in Object, I have a JSON Code like this '{ "42": "42 Coin", "365": "365Coin", "404": "404Coin", "611": "SixEleven", "808": "808", "888": "Octocoin", "1337": "1337", "2015": "2015 coin", "CLUB": " ClubCoin", "007": "007 coin", "ZRX": "0x", "BIT16": "16BitCoin" } How can i convert this to JSONObject to JSONArray
0
JSONObject Jobj = new JSONObject(result.toString());
JSONArray Jarray = obj.getJSONArray("value");

What you need is Jarray.

And then iterate Jarray to get the objects and values Longitude,Latitude in the objects.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.