hannsworst hannsworst - 5 months ago 8
JSON Question

How to return a from json converted array in java?

The following code works fine(!), i wnat to moved it into a own function, but i cant return the from json converted Array (last line). What im doing wronng?

public Array jsonToArray(String json) {

JSONObject myjson = null;
try {
myjson = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray the_json_array = null;
try {
the_json_array = myjson.getJSONArray("profiles");
} catch (JSONException e) {
e.printStackTrace();
}
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = null;
try {
another_json_object = the_json_array.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}

arrays.add(another_json_object);
}

JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

return Array jsons;
}


I think the Problem is the Type, but im completely new in JAVA... Im getting the error: 'Not a statement'. What is the meaning and the Solution?

Answer
public JSONObject[] jsonToArray() 

As well as

return jsons;

Or, why not return the ArrayList<JSONObject>, why bother with another conversion?

Though, ideally, returning an actual JSONArray object instead of a Java array of JSONObject makes more sense.

Such as

return myjson.getJSONArray("profiles");

Or, one step further, actually parsing out the values of the JSON you want into your own Java classes?