繁体   English   中英

如何从java中的json转换数组返回一个?

[英]How to return a from json converted array in java?

下面的代码工作正常(!),我将其移至自己的函数中,但无法从json转换后的Array返回(最后一行)。 我在做什么?

    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;
}

我认为问题是类型,但是在JAVA中是全新的...我收到错误:“不是声明”。 含义和解决方案是什么?

public JSONObject[] jsonToArray() 

以及

return jsons;

或者,为什么不返回ArrayList<JSONObject> ,为什么还要进行其他转换呢?

不过,理想情况下,返回实际的JSONArray对象而不是JSONObject的Java数组更有意义。

return myjson.getJSONArray("profiles");

或者,更进一步,实际上是将所需的JSON值解析为自己的Java类吗?

你应该做:

return jsons;

还要更正返回类型,您在其中有Array ,我没有在代码的任何位置看到该类型,并且在Java中也没有这种类型,您可能需要JSONObject[] ,因此方法的第一行是:

public JSONObject[] jsonToArray(String json) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM