【问题标题】:How to get Jsonobject from list in java?如何从java中的列表中获取Jsonobject?
【发布时间】:2019-01-31 05:30:29
【问题描述】:

我有两个 jsonobject 在列表中。如果我创建新的 jsonobject 并尝试获取列表,它会给我 null。

代码在下面-

    private int isExisting(String pid, List profile, String size) throws JSONException {
       for (int i = 0; i < profile.size(); i++) {
           JSONObject obj = new JSONObject(profile.get(i));
           log.info("--------------" + obj.toString());   //it is giving me an empty object but list contains two objects {"size":"M","id":11} and {"size":8,"id":19}
       }
    }

【问题讨论】:

  • 可能会显示调用您的方法的代码以及您传递给它的内容。
  • 您也可以发布您的示例数据

标签: java json list


【解决方案1】:

我试过了,效果很好

private void isExisting(String pid, List profile, String size) throws JSONException {
    for (int i = 0; i < profile.size(); i++) {
        if(profile.get(i)!=null) {
            JSONObject obj = new JSONObject(profile.get(i).toString());
            System.out.print("keys----------" + obj.toString());  
        }
    }
}

public void processList() {
    try {
        JSONObject objA= new JSONObject("{\n" +
                "      \"size\": \"M\",\n" +
                "      \"id\": 11\n" +
                "    }");
        JSONObject objB=new JSONObject("{\n" +
                "      \"size\": 8,\n" +
                "      \"id\": 19\n" +
                "    }");

        List<JSONObject> list=new ArrayList<>();
        list.add(objA);
        list.add(objB);
        isExisting("",list,"");
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

【讨论】:

    【解决方案2】:

    我已经尝试过这个简单的逻辑,它运行良好-

    private int isExisting(String pid, List profile, String size) throws JSONException {
           for (int i = 0; i < profile.size(); i++) {
               JSONObject obj = (JSONObject) profile.get(i);
               log.info("--------------" + obj.toString());   
           }
        }
    

    【讨论】:

      猜你喜欢
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 2020-03-01
      相关资源
      最近更新 更多