How to convert POJO to JSON and vice versa?

前端 未结 6 736
忘了有多久
忘了有多久 2020-11-27 15:40

I want to know if there is any Java API available to convert a POJO object to a JSON object and vice versa.

6条回答
  •  遥遥无期
    2020-11-27 16:18

    If you are aware of Jackson 2, there is a great tutorial at mkyong.com on how to convert Java Objects to JSON and vice versa. The following code snippets have been taken from that tutorial.

    Convert Java object to JSON, writeValue(...):

    ObjectMapper mapper = new ObjectMapper();
    Staff obj = new Staff();
    
    //Object to JSON in file
    mapper.writeValue(new File("c:\\file.json"), obj);
    
    //Object to JSON in String
    String jsonInString = mapper.writeValueAsString(obj);
    

    Convert JSON to Java object, readValue(...):

    ObjectMapper mapper = new ObjectMapper();
    String jsonInString = "{'name' : 'mkyong'}";
    
    //JSON from file to Object
    Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
    
    //JSON from URL to Object
    Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);
    
    //JSON from String to Object
    Staff obj = mapper.readValue(jsonInString, Staff.class);
    

    Jackson 2 Dependency:

    
        com.fasterxml.jackson.core
        jackson-databind
        2.6.3
    
    

    For the full tutorial, please go to the link given above.

提交回复
热议问题