如何将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 '[]'.

duanchen7703
duanchen7703 arraylist和json数组之间的唯一区别是每条记录之间现在没有空格。如何摆脱所有与JSON相关的字符,只留下像[shampoo.png,hobnobs.png,shrek.jpg]这样的字符串数组?
3 年多之前 回复
dongqie8661
dongqie8661 好吧,我设法让它记录长度,即5,并且ArrayList现在记录这个[{“advert_File_Path”:“toothpaste.jpg”},{“advert_File_Path”:“moisturizer.jpg”},{“advert_File_Path”:“shampoo.jpg”},{“advert_File_Path”:“hobnobs.png”},{“advert_File_Path”:“shrek.jpg”}]
3 年多之前 回复
dpvomqeu396484
dpvomqeu396484 我设法删除了数组<!-->,似乎是注释的代码以某种方式突破。我记录了数组的长度,但没有出现System.out
3 年多之前 回复
duan0513
duan0513 最后一个数组<!-->也是输出字符串的一部分吗?并且,请记录以查看jsonArray的长度。
3 年多之前 回复
dongxikuo5171
dongxikuo5171 trystringList.add(jsonArray.getJSONObject(i).optString(“advert_File_Path”));
3 年多之前 回复
duanlongling5308
duanlongling5308 嗨Lym,输出看起来像这样[{“advert_File_Path”:“toothpaste.jpg”},{“advert_File_Path”:“moisturizer.jpg”},{“advert_File_Path”:“shampoo.jpg”},{“advert_File_Path”:“hobnobs.png”},{“advert_File_Path”:“shrek.jpg”}]数组<!-->
3 年多之前 回复
duanjianxiu9400
duanjianxiu9400 输出字符串的格式是什么?或者更好,显示输出字符串。
3 年多之前 回复

4个回答



管理自己解决它。
所以这里,</ p>

步骤1.我 不得不删除我的php文件中的注释代码,因为它突破了某种方式,那就是来自JSON数组末尾的那些。


Step 2.我不得不从php文件中删除一个额外的echo 我用它来进行错误检查。 我认为我说你想要的唯一回应是json_encode。


Step 3.检查Java中JSONarray的长度并记录5,所以我现在知道它正确读取了。


Step 4.添加了Pavneet_Singh的代码片段,用 stringList.add(jsonArray)替换 stringList.add(jsonArray.get(i).toString());
</ code> .getJSONObject(i).optString(“advert_File_Path”));
</ code>


Step 5.使用此代码将codeList中的stringList转换为String数组 stringArray = new String [ stringList.size()];
stringArray = stringList.toArray(stringArray); </ code>


天快! 我花了很长时间试图弄清楚哈哈,前两个步骤是相当noobish但它有时是最难找到的生活中最明显的事情。 希望这也可以帮助其他人!</ p>
</ div>

展开原文

原文

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!



使用 stringList.add(jsonArray.getString(i)); </ code> </ p>
</ DIV>

展开原文

原文

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

douchigu1723
douchigu1723 虽然此代码可以回答这个问题,但提供有关如何和/或解决问题的原因的其他背景将提高答案的长期价值。 提及为什么这个答案比其他答案更合适也没有什么坏处。
3 年多之前 回复
dongxun6690
dongxun6690 不起作用,完全相同:/
3 年多之前 回复



试试这个:</ p>

  JSONArray arr = new JSONArray(putNesessaryValueHere); 
List&lt ;字符串&GT; list = new ArrayList&lt; String&gt;();
for(int i = 0; i&lt; arr.length(); i ++){
list.add(arr.getJSONObject(i).getString(“name”)) ;
}
</ code> </ pre>
</ div>

展开原文

原文

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



 试试这个:

ArrayList&lt; String&gt; arrayList = new ArrayList&lt; String&gt;();
JSONArray jsonArray = new JSONArray();
for(int i = 0,count = jsonArray.length(); i&lt; count; i ++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
arrayList.add(jsonObject.toString());
}
catch(JSONException e){
e.printStackTrace();
}
}
</ code> </ pre>
</ div>

展开原文

原文

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐