首页 > 解决方案 > 如何在Java中返回两个以上的地图对象

问题描述

实际上我正在尝试在同一个类中解析两个 api 的 json 数据。我知道不应该这样做,但这是要求。我正在从哈希图中获取数据。我想将它添加到表中。但问题是程序只添加了表中的最后一项。但是在调试时它会给出所有值。

这是我的代码:

public class services2
{
    public Map<Object, Object> getReportees(String idOfEmp) throws  Exception {
        ......
        if(resp.getStatus() != 200){
            System.err.println("Unable to connect to the server");
        }
        String output = resp.getEntity(String.class);
        //Store the JSON objects in an array
        //Get the index of the JSON object and print the values as per the index
        JSONParser parse = new JSONParser();
        JSONObject jobj = (JSONObject)parse.parse(output);
        JSONArray jsonarr_1 = (JSONArray) jobj.get("list");
        Map<Object, Object> map=new HashMap<Object,Object>();
        for(int i=0;i<jsonarr_1.size();i++){
            JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
            JSONObject jive      = (JSONObject)jsonobj_1.get("jive");
            String var   = jive.get("username").toString();
            values = var;
            if(resp1.getStatus() != 200){
                system.err.println("Unable to connect to the server");
            }
            String output1 = resp1.getEntity(String.class);
            JSONObject jobjs = (JSONObject) new JSONParser().parse(output1);

            JSONArray jsonarr_11 = (JSONArray) jobjs.get("issues");
            System.out.println("count"+jsonarr_11.size());
            Object obj3 = jsonarr_11.size();
            int counter = (Integer) obj3;
            System.out.println(counter);

            Object obj1 = jsonobj_1.get("displayName");
            Object obj2 = jive.get("username");

            map.put(obj1, obj2);
            map.put("obj3", obj3);
            System.out.println(obj3);
        }
        return  map;  //for the map obj3 return only the last count that is 1
    }
} 

在这里,当我尝试发送地图 obj3. 我只得到最后一个值。我实际上希望以正确的方式进行计数。

                    This is the output:
             Number  id     username       count
               1    A12345  Anagha R        1
               2    M12345  Madhusudan S    1
               3    AT12345 Amreen Taj      1
                   Expected output is:
               1    A12345  Anagha R        0
               2    M12345  Madhusudan S    0
               3    AT12345 Amreen Taj      1

当我尝试在控制台中打印时,它给了我正确的计数,但是当我尝试通过地图时,它只发送最后一个值为 1 的值。

标签: java

解决方案


问题出在下面的代码行中:

map.put("obj3", obj3);

每次您替换“Obj3”的值而不是增加地图的现有值时。

相反,您需要做的是:

if(map.containsKey("obj3")
{
    Object obj3 = map.get("obj3");
    //put your logic of incrementing or adding the count 
    //Lets say it is new Value
    map.put("obj3",newValue)
}

推荐阅读