douji8017
douji8017
2017-03-21 15:33

如何将JSON数组转换为Java String数组

已采纳

I have a php file which fetches all rows from a specific column. The result is then put into an array and then json_encoded. When I Toast the output from the php file it shows a JSON string with the correct values. I need to convert this to a Java String array so I can iterate through it one by one on a button click.
I've tried multiple solutions on here but to no avail so any help will be greatly appreciated!

getImage.php

$sql = "SELECT advert_File_Path FROM Ads";
$result = $mysql_con->query($sql) or die('Query problem: '.mysqli_error($mysql_con));

//create array
$resultarray = array();

while($row = mysqli_fetch_assoc($result)){
    $resultarray[] = $row;
}
echo json_encode($resultarray);

MainActivity.java (only the code that is relevant)

 private void loadNextAdvert()
{
    Toast.makeText(this, "Please wait, image may take a few seconds to load...", Toast.LENGTH_LONG).show();

    dbhelper = (DbHelper) new DbHelper(new DbHelper.AsyncResponse() {
        @Override
        public void processFinish(String output) {
            if(output.equalsIgnoreCase("exception") || output.equalsIgnoreCase("unsuccessful")){
                Toast.makeText(MainActivity.this, "Connection error", Toast.LENGTH_SHORT).show();
            }else{
                //initializes ArrayList
                stringList = new ArrayList<>();
                try {
                    //initializes JSONArray with output from php getImage file
                    jsonArray = new JSONArray(output);
                    if(jsonArray != null){
                        int len = jsonArray.length();
                        for(int i=0; i<len; i++){
                            stringList.add(jsonArray.get(i).toString());
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Toast.makeText(MainActivity.this, String.valueOf(stringList), Toast.LENGTH_LONG).show();
            }
        }
    }).execute(loadPic);
}

The Toast which should display the contents of the ArrayList just appears as '[]'.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • douge3113 douge3113 4年前

    Managed to solve it myself.
    So here goes,

    Step 1. I had to remove commented code from my php file as it was breaking through somehow, thats where the came from at the end of the JSON array.

    Step 2. I had to remove an additional echo from the php file which I was using for error checking. I think I'm right in saying the only echo you want to have is the json_encode.

    Step 3. Checked the length of JSONarray in Java and it was logging 5 so I now knew it was reading correctly.

    Step 4. Added Pavneet_Singh's code snippet to replace stringList.add(jsonArray.get(i).toString()); with stringList.add(jsonArray.getJSONObject(i).optString("advert_File_Path"));

    Step 5. Converted stringList from an ArrayList to a String array using this code stringArray = new String[stringList.size()]; stringArray = stringList.toArray(stringArray);

    Happy days! I've spent far too long trying to figure this out haha the first two steps are pretty noobish but it's sometimes the most obvious things in life that are the hardest to find. Hopefully this can help someone else too!

    点赞 评论 复制链接分享
  • dtr87341 dtr87341 4年前
    Try this : 
    
    ArrayList<String> arrayList = new ArrayList<String>();
    JSONArray jsonArray = new JSONArray();
    for(int i = 0, count = jsonArray.length(); i< count; i++)
    {
        try {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            arrayList.add(jsonObject.toString());
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }
    
    点赞 评论 复制链接分享
  • doudong7256 doudong7256 4年前

    Try this:

    JSONArray arr = new JSONArray(putNesessaryValueHere);
    List<String> list = new ArrayList<String>();
    for(int i = 0; i < arr.length(); i++){
        list.add(arr.getJSONObject(i).getString("name"));
    }
    
    点赞 评论 复制链接分享
  • dongliang1654 dongliang1654 4年前

    use stringList.add(jsonArray.getString(i));

    点赞 评论 复制链接分享

为你推荐