Convert json string to Java Map(JSONLib)

天涯浪子 提交于 2020-01-01 08:02:51

问题


How can I convert json string to Java Map using JSON-lib(http://json-lib.sourceforge.net/) ? I can convert to DynaBean:

JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );  
DynaBean bean = (DynaBean) JSONSerializer.toJava( jsonObject );  

but I have not found a method to convert directly to Java Map

Edit:

I have found the solution:

JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );
Map<String, Object> myMap = (Map<String, Object>) JSONObject.toBean(jsonObject, Map.class)

回答1:


Another approach is to take advantage of the fact that a JSONObject implements java.util.Map. So, it is a map.

import java.util.Map;

import net.sf.json.JSONObject;

public class Foo
{
  static String json = "{\"one\":\"won\",\"two\":2,\"three\":false}";

  public static void main(String[] args)
  {
    JSONObject jsonObject = JSONObject.fromObject(json);
    Map map = jsonObject;
    System.out.println(map);
  }
}


来源:https://stackoverflow.com/questions/6323205/convert-json-string-to-java-mapjsonlib

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!