简体   繁体   中英

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?

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?

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) {

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