My question is almost identical to the one below.
Get JSONArray without array name?
Forgot to mention this thread as well: Parse json array android
I'm parsing the following data. https://api.tfl.gov.uk/Line/Mode/tube%2Cdlr
I just need to extract "id" and "name". Like in the thread above, the data is enclosed in square brackets but not in a specific array. I need to parse a JSON object and then return the data in an ArrayList. I know how to parse an ArrayList. When parsing, do I create a JSON object or a JSON Array? Is it possible to create and parse a JSONObject and then convert it to and return it in an array?
In the first example they use HashMap. Is it possible to parse it w/o HashMap and GSON? And in the second thread, they extract the data from the Url in the try catch method. I implemented BuildUrl method in a separate class.
P.S. I haven't tested the code yet.
JSONUtils class:
public class JSONUtils
{
/**
* Tag for the log messages
*/
private static final String LOG_TAG = JSONUtils.class.getSimpleName();
private static final String KEY_LINE_ID = "id";
private static final String KEY_LINE_NAME = "name";
public JSONUtils()
{
}
public static Lines extractFeatureFromJson (String linesJSON)
{
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(linesJSON)) {
return null;
}
Lines line = null;
try
{
// Create a JSONObject from the JSON file
JSONObject jsonObject = new JSONObject(linesJSON);
String id = "";
if (jsonObject.has("id"))
{
id = jsonObject.optString(KEY_LINE_ID);
}
String name = "";
if (jsonObject.has("name"))
{
name= jsonObject.optString(KEY_LINE_NAME);
}
line = new Lines(id, name);
}
catch (JSONException e)
{
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing lines JSON results", e);
}
// Return the list of lines
return line;
}
}
You can try like this following:
You will have to pass your response and I just put all your response in
String
. You can pass your own response from API on that behalf.It will give you
id
andname