【问题标题】:How to read second array from json arrays in Android如何从Android中的json数组中读取第二个数组
【发布时间】:2020-03-27 10:41:02
【问题描述】:

我正在尝试从同一个请求中读取两个 json 数组
JSON 文件:

{
"items": [
  {
    "title": "welcoem home",
    "author": "Charles Dickens"
  },
  {
    "title": "Harry Potter",
    "author": "J rowling"
  }]
}
{
"items1": [
  {
    "title": "welcoem home",
    "author": "Charles Dickens"
  },
  {
    "title": "Harry Potter",
    "author": "J rowling"
  }]
}

我用来阅读的代码是:

 //Convert JSON to String and gets our app version
    private String getJSON(String JSON_STRING){

        try {
            //Objects
            jsonObject=new JSONObject(JSON_STRING);
            jsonArray=jsonObject.getJSONArray("items");
            //Variables
            int count=0;
            String tempTitle, temAuthor;

            while (count<jsonArray.length()){

                //Reads Row by Row
                JSONObject JO= jsonArray.getJSONObject(count);
                tempTitle= JO.getString("title");
                temAuthor= JO.getString("author");

                //If our App found
                if (Constants.Title.equals(tempTitle)){

                    return temAuthor;
                }

                count++;

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return "Not Found!";
    }

但是当我调用读取第二个表(如 items1)时,它说没有找到表? 我试图在表之间添加一个 (,) 但相同,我是 php 和 android 的新手,所以我很难更改代码,所以这对我来说是任何简单的方法,我的意思是任何改变更少代码的方法让它工作,或者我必须完全改变我的android方法?

【问题讨论】:

  • 您的json 格式错误。先改正

标签: android arrays json parsing


【解决方案1】:

我找到了对我来说最简单的方法,@Michael Jaison 的回答也可以,但我找到了最简单的方法,我只是阅读了所有加入的两个 json 表,比如

{table1}###{table2}

然后在 android 中读取所有文件,然后拆分字符串:

String[] splitedResult = result.split("###");

所以我到了桌子

splitedResult[0] = { "items": [...
splitedResult[1] = { "items1": [...

然后只是将字符串传递给方法来读取它:) 哇哇它工作了:)

【讨论】:

    【解决方案2】:

    试试下面的 JSON 代码,

    {
      "items": [
      {
        "title": "welcoem home",
        "author": "Charles Dickens"
      },
      {
        "title": "Harry Potter",
        "author": "J rowling"
      }]
      ,
      "items1": [
      {
        "title": "welcoem home",
        "author": "Charles Dickens"
      },
      {
        "title": "Harry Potter",
        "author": "J rowling"
      }]
    }
    

    您可以在任何在线解析器中检查您的 JSON 代码的有效性,例如 http://json.parser.online.fr/

    【讨论】:

      猜你喜欢
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 2016-08-26
      • 2020-08-18
      • 2011-05-13
      • 1970-01-01
      • 2018-01-24
      相关资源
      最近更新 更多