如何在Map.Entry上循环(for / while / loop)

时间:2013-05-09 10:50:17

标签: java json map

我在Map中有一个带有jSON的Map.Entry,我希望将这个值设为Map

通过示例,可以更容易地解释: 我正在对这样的URL做api请求:

response1 = httpclient.execute(httpGet);

这是我从请求中得到的JSON:

{"Projects":
  [{"Role":"ProjectAdmin","Url":"http://**/","OverSized":false,"Folders":      
     [{"Name":"sh","Url":"http://**/","Permssion":"rw"}]},
   {"Role":"ProjectAdmin","Url":"http://**/Goooood","OverSized":false,"Folders":     
     [{"Name":"Goooood","Url":"http://**/Goooood","Permssion":"rw"}]}],
 "DeviceToken":"token",
 "TotalProjects":2}

这就是我将JSON转换为MAP的方式:

ContainerFactory containerFactory = new ContainerFactory()
{
  public List creatArrayContainer() {return new LinkedList();}
  public Map createObjectContainer() {return new LinkedHashMap();}
};
BufferedReader br = new BufferedReader(new InputStreamReader(response1.getEntity().getContent()));
StringBuilder content = new StringBuilder();
String line;
//TODO:Remove and build a better JSON parser
while (null != (line = br.readLine()))
{
   content.append(line);
}
JSONParser parser = new JSONParser();    
try
{
  json = (Map)parser.parse(content.toString(), containerFactory);
  Iterator iter = json.entrySet().iterator();
}

现在一切都很棒! 现在我可以在iter上做一段时间 像这样:

while(iter.hasNext())
{
   Map.Entry entry = (Map.Entry)iter.next();
   System.out.println(entry.getKey() + "=>" + entry.getValue());
}

现在我的问题是我有一个entry.getValue()里面有json。

示例:

   [{"Role":"ProjectAdmin","Url":"http://**/","OverSized":false,"Folders":      
     [{"Name":"sh","Url":"http://**/","Permssion":"rw"}]},
   {"Role":"ProjectAdmin","Url":"http://**/Goooood","OverSized":false,"Folders":     
     [{"Name":"Goooood","Url":"http://**/Goooood","Permssion":"rw"}]}]

我需要从响应中创建一个Map才能循环它。 有没有办法做到这一点 ? 有没有办法做得对?

我不认为将它作为一个字符串变成一个问题就像我在开始时所做的一样,但我觉得有更好的方法。

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试根据您的对象映射此代码

 Iterator<Entry<Long, String>> it = 
   yourMap.entrySet().iterator();
    while (it.hasNext()) {
    Map.Entry<Long, String> pairs = (Map.Entry<Long, String>) it.next();
        bw.write(pairs.getValue());
    }

希望这会有所帮助。

相关问题