0

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?

3
  • return Array jsons; isn't valid syntax... return jsons; is, but it's unclear if that is what you want Jun 11, 2016 at 19:04
  • 1
    The above code does not compile Jun 11, 2016 at 19:06
  • Yeah, the code does not, in fact, "work fine" unless it actual runs Jun 11, 2016 at 19:09

2 Answers 2

1
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?

0
0

You should do:

return jsons;

And also correct the return type, you have Array there, I don't see that type defined anywhere in your code, and there is no such type in java, you probably wanted JSONObject[], so the first line of the method will be:

public JSONObject[] jsonToArray(String json) {
2
  • Hmm, doesnt work, too. i tried: "return jsons;" If i move the mouse over the return statement i get: Incompatible types; Required List; Found: org.json.JSONObject[]
    – hannsworst
    Jun 11, 2016 at 19:09
  • @hannsworst You need to replace Array with JSONObject[] Jun 11, 2016 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.