将字符串从json编码的数组放入Java ArrayList。

时间:2022-10-24 14:01:37

I've created an array and have filled it with row values from an SQL database, and then encode the array into a JSON object:

我创建了一个数组,并从SQL数据库中填充了行值,然后将数组编码为JSON对象:

$league = array();

while(mysqli_stmt_fetch($result)){
    $league[] = $leagueName;
}

json_encode($league);

How would I go about retrieving the items from the array, and then inserting them into an ArrayList? I currently have this in my Java code:

如何从数组中检索项,然后将它们插入到数组列表中?我现在在Java代码中有这个:

HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);

Currently, "result" takes the format: "["leagueA", "leagueB", "leagueC"]", where I would have liked to have seen something like "[0:"leagueA", 1:"leagueB", 2:"leagueC"]" so that I can have reference the returned values in a loop. Is there any way to insert the returned values into an ArrayList without manually parsing returned "result"?

目前,“结果”采用了格式:“(“leagueA”,“leagueB”,“leagueC”),在这里我希望看到一些类似的东西:“leagueA”,1:“leagueB”,2:“leagueC”),这样我就可以在循环中引用返回的值。是否有方法将返回的值插入到ArrayList中,而无需手动解析返回的“结果”?

1 个解决方案

#1


0  

I was able to solve this issue by simply creating a JSONArray (instead of JSONObject) like so:

我可以简单地创建一个JSONArray(而不是JSONObject)来解决这个问题:

HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            JSONArray jsonArray = new JSONArray(result);
            //JSONObject jObject = new JSONObject(result);
            if(jsonArray.length() == 0){
                returnedLeague = null;
            }
            else{
                for(int i = 0; i < jsonArray.length(); i++){
                    returnedLeague.add(jsonArray.getString(i));
                }
            }

Turns out, a JSONArray can be created from a string if it is properly formatted, which the json_encode function did for me.

原来,如果json_encode函数正确格式化,那么可以从字符串中创建一个JSONArray。

#1


0  

I was able to solve this issue by simply creating a JSONArray (instead of JSONObject) like so:

我可以简单地创建一个JSONArray(而不是JSONObject)来解决这个问题:

HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            JSONArray jsonArray = new JSONArray(result);
            //JSONObject jObject = new JSONObject(result);
            if(jsonArray.length() == 0){
                returnedLeague = null;
            }
            else{
                for(int i = 0; i < jsonArray.length(); i++){
                    returnedLeague.add(jsonArray.getString(i));
                }
            }

Turns out, a JSONArray can be created from a string if it is properly formatted, which the json_encode function did for me.

原来,如果json_encode函数正确格式化,那么可以从字符串中创建一个JSONArray。