Question

Comment puis-je convertir la chaîne JSON à Java en utilisant la carte JSON-lib (http://json-lib.sourceforge.net/)? Je peux convertir en DynaBean:

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

mais je ne l'ai pas trouvé une méthode pour convertir directement à Java Carte

Modifier

J'ai trouvé la solution:

JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );
Map<String, Object> myMap = (Map<String, Object>) JSONObject.toBean(jsonObject, Map.class)
Était-ce utile?

La solution

Une autre approche consiste à tirer profit du fait qu'un JSONObject met en œuvre java.util.Map. Ainsi, il une carte.

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);
  }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top