【问题标题】:How to differentiate value of array with two object with same key in javajava - 如何区分数组的值与Java中具有相同键的两个对象
【发布时间】:2015-08-25 11:15:01
【问题描述】:

我正在实现一个 Android 应用。我有一个 100 行 2 列的谷歌电子表格。我正在我的应用程序中获取谷歌电子表格的记录。我得到了这样的 JSON 响应:

JSON Response

{
     "version": "0.6",
      "reqId": "0",
      "status": "ok",
      "sig": "862971983",
      "table": {
        "cols": [
          {
            "id": "A",
            "label": "Name",
            "type": "string"
          },
          {
            "id": "B",
            "label": "PhoneNo",
            "type": "number",
            "pattern": "General"
          }
        ],
        "rows": [
          {
            "c": [
              {
                "v": "A Anil C Agrawal"
              },
              {
                "v": 7926605853,
                "f": "7926605853"
              }
            ]
          },
          {
            "c": [
              {
                "v": "A Balaji Agarwal"
              },
              {
                "v": 8463225752,
                "f": "8463225752"
              }
            ]
          },.................

这里我有 C 是数组类型,其中两个对象具有相同的键,但我希望在 Ex 的不同变量中使用相同的键。字符串名称,字符串电话号码。

这是我获取谷歌电子表格响应并打印它的方法。如果我打印 Name 的值,那么它会同时显示 Name 和电话号码,但我想要 Name= Abc 和 PhoneNo = 8574968521。

public void getSpreadSheetData() {
        String result = getSpreadSheetResponce();
        List<String> arrayList = new ArrayList<String>();
        if (result == null) {
            Log.e("net not present:", "");
        } else {
            int start = result.indexOf("{", result.indexOf("{") + 1);
            int end = result.lastIndexOf("}");
            String jsonResponse = result.substring(start, end);

            try {
                JSONObject mainObj = new JSONObject(jsonResponse);
                String Name = null;

                if (mainObj != null) {
                    JSONArray list = mainObj.getJSONArray("rows");
                    if (list != null) {
                        for (int i = 0; i < list.length(); i++) {
                            JSONObject innerJsonObject = list.getJSONObject(i);
                            if (innerJsonObject != null) {
                                //
                                JSONArray valuesJsonArray = innerJsonObject
                                        .getJSONArray("c");
                                if (valuesJsonArray != null) {
                                    for (int j = 0; j < valuesJsonArray
                                            .length(); j++) {
                                        JSONObject innerElem = valuesJsonArray
                                                .getJSONObject(j);
                                        if (innerElem != null) {
                                            Name = innerElem.getString("v");
                                            arrayList.add(Name);
                                            Log.i("arrayList", "" + arrayList);

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

    }

    private String getSpreadSheetResponce() {

        String responce = " ";
        String urlString = "";
        try {
            String FETCH_ROW_WITH_WHERE_CLAUSE_URL = "https://spreadsheets.google.com/tq?tq&key=1n_VjwHm8qIU5YRMM-wMkJIap2KZa5vOfxWI5dpYT1PE&gid=1262286779";
            URL urlspreadsheet = new URL(FETCH_ROW_WITH_WHERE_CLAUSE_URL);
            URLConnection urlConnection = urlspreadsheet.openConnection();
            HttpURLConnection connection = null;
            if (urlConnection instanceof HttpURLConnection) {
                connection = (HttpURLConnection) urlConnection;
            } else {
                System.out.println("Please enter an HTTP URL.");
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String current;

            while ((responce = in.readLine()) != null) {
                urlString += responce;
                System.out.println(urlString);
                Log.e("Response::", "in loop:" + urlString);
            }
            Log.e("Response::", "final response:" + urlString);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return urlString;

    }  

有可能吗,请帮帮我。

【问题讨论】:

  • 你确定c数组中只有两个对象吗?然后您可以使用循环中元素的位置检查它们并将其分配到您想要的任何位置否则我没有正确理解它
  • 是的,我确定。您可以看到 JSON 响应。这一切都清楚你的查询。 @Dev

标签: android json arraylist google-sheets


【解决方案1】:

你不需要通过 json 对象名来获取这个数组。 意味着您必须在此处使用 Object 键。

//JSONObject c = Jsonobj.getJSONObject("row");
//convert your jsonarray in json object
Iterator<String> it = c.keys();// check for first and next object
while (it.hasNext()) { // call while we have next object in array
String Key = it.next(); // this will get next obj name in string "c"
JSONObject keyobj = new JSONObject(c.toString()); // this will gat "c" object array from json
  1. 在 Json 对象中获取“行”数组
  2. 现在不获取对象“c”,而是在这里使用对象键方法
  3. 检查直到“行”数组没有任何对象
  4. 在您的 JSON 中,此方法将调用两次,您将轻松获得具有相同对象名称的所有数据

【讨论】:

    【解决方案2】:

    @abc 请用这个方法。它会解决你的问题。如果有任何问题,请在下方评论。

    private void json(String jsonString) {
    arrayList = new ArrayList<>();
    JSONObject mainObj = null;
    try {
      mainObj = new JSONObject(jsonString);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    String Name = null;
    
    if (mainObj != null) {
      try {
        JSONObject tableObject = mainObj.getJSONObject("table");
          JSONArray rowMasterArray = tableObject.getJSONArray("rows");          
          if (rowMasterArray != null) {
            for (int i = 0; i < rowMasterArray.length(); i++) {
              JSONObject rowsObject= rowMasterArray.getJSONObject(i);
              if (rowsObject != null) {
                  JSONArray rowsItemArray = rowsObject.getJSONArray("c");
                  if (rowsItemArray != null) {
                    for (int k = 0; k < rowsItemArray.length(); k++) {
                      JSONObject innerElem = rowsItemArray.getJSONObject(k);
                      if (innerElem != null) {
                        Name = innerElem.getString("v");
                        arrayList.add(Name);
                        Log.i("arrayList", "" + arrayList);
                      }
                    }
                  }
              }
            }
          }
      }catch (JSONException e) {
          e.printStackTrace();
        }
      }
    }
    

    【讨论】:

    • 好的,谢谢,但是您在哪里打印电话号码的值?
    • @abc 嘿,我看到了您的帖子...我想您已经知道如何获取电话号码了。所以我觉得我的回答也可以接受。
    【解决方案3】:

    我得到了我的问题的解决方案。我对 getSpreadSheetData() 方法做了一些更改。
    在这里我犯了一些逻辑错误,现在它解决了

    public void getSpreadSheetData() {
            hashMap = new HashMap<Integer, String>();
            String result = getSpreadSheetResponce();
            List<String> arrayList = new ArrayList<String>();
            if (result == null) {
                Log.e("net not present:", "");
            } else {
                int start = result.indexOf("{", result.indexOf("{") + 1);
                int end = result.lastIndexOf("}");
                String jsonResponse = result.substring(start, end);
    
                try {
                    JSONObject mainObj = new JSONObject(jsonResponse);
                    String Name = null;
    
                    if (mainObj != null) {
                        JSONArray list = mainObj.getJSONArray("rows");
                        if (list != null) {
                            for (int i = 0; i < list.length(); i++) {
                                JSONObject innerJsonObject = list.getJSONObject(i);
                                if (innerJsonObject != null) {
                                    //
                                    JSONArray valuesJsonArray = innerJsonObject
                                            .getJSONArray("c");
                                    if (valuesJsonArray != null) {
                                        for (int j = 0; j < 1; j++) {
                                            JSONObject innerElem = valuesJsonArray
                                                    .getJSONObject(j);
                                            if (innerElem != null) {
                                                Name = innerElem.getString("v");
                                                // arrayList.add(Name);
                                                Log.e("name no:",
                                                        "" + Name.toString());
                                                JSONObject SecondElement = valuesJsonArray
                                                        .getJSONObject(j + 1);
                                                if (SecondElement != null) {
                                                    String phone = SecondElement
                                                            .getString("f");
                                                    Log.e("Phone no:",
                                                            "" + phone.toString());
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    Log.e("Name Last", "" + Name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-18
      • 2018-05-22
      • 2018-01-13
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 2021-08-19
      相关资源
      最近更新 更多