Convert JSON to Map

后端 未结 17 3220
天涯浪人
天涯浪人 2020-11-22 10:20

What is the best way to convert a JSON code as this:

{ 
    \"data\" : 
    { 
        \"field1\" : \"value1\", 
        \"field2\" : \"value2\"
    }
}
         


        
17条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 11:04

    If you need pure Java without any dependencies, you can use build in Nashorn API from Java 8. It is deprecated in Java 11.

    This is working for me:

    ...
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    ...
    
    public class JsonUtils {
    
        public static Map parseJSON(String json) throws ScriptException {
            ScriptEngineManager sem = new ScriptEngineManager();
            ScriptEngine engine = sem.getEngineByName("javascript");
    
            String script = "Java.asJSONCompatible(" + json + ")";
    
            Object result = engine.eval(script);
    
            return (Map) result;
        }
    }
    

    Sample usage

    JSON:

    {
        "data":[
            {"id":1,"username":"bruce"},
            {"id":2,"username":"clark"},
            {"id":3,"username":"diana"}
        ]
    }
    

    Code:

    ...
    import jdk.nashorn.internal.runtime.JSONListAdapter;
    ...
    
    public static List getUsernamesFromJson(Map json) {
        List result = new LinkedList<>();
    
        JSONListAdapter data = (JSONListAdapter) json.get("data");
    
        for(Object obj : data) {
            Map map = (Map) obj;
            result.add((String) map.get("username"));
        }
    
        return result;
    }
    

提交回复
热议问题