Search code examples
javajsonjspjson-libjson-simple

Convert JSON String to Java object for easy use in JSP


Is their an easy way or library to convert a JSON String to a Java object such that I can easily reference the elements in a JSP page? I think Map's can be referenced with simple dot notation in JSP pages, so JSON -> Map object should work?

UPDATE: Thank you for all the JSON Java libraries. In particular, I'm looking for a library that makes it easy for consumption in JSP pages. That means either the Java object created has appropriate getter methods corresponding to names of JSON nodes (is this possible?) or there's some other mechanism which makes it easy like the Map object.


Solution

  • Use Jackson.

    Updated:

    If you have an arbitrary json string Jackson can return a map object to access the properties values.

    Here a simple example.

    @Test
    public void testJsonMap() throws JsonParseException, JsonMappingException, IOException {
        String json = "{\"number\":\"8119123912\",\"msg\":\"Hello world\"}";
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String,Object>>() { });
        System.out.println("number:" + map.get("number") + " msg:" + map.get("msg"));
    }
    

    Output:

    number:8119123912 msg:Hello world