Search code examples
javajsonjax-rsjava-ee-7

JSON: Object to JsonString - JsonString to X.class Object


I've got a class called MediaList and I want to parse this class with values to a JSON-String and backwards.

public class KeywordList {
       private List<Keyword> keywords = new ArrayList<>();
}

And here the JSON-String:

{
    "keywords": [
        {
            "id": 12,
            "name": "Thesis",
            "mediaCount": 31
        }, ...
    ]
}

I'm using google lib gson, but i just want to use the standard java version with jax-rs because i don't want 3rd party tools to be in my project.


Solution

  • Unfortunately you have to use external libraries cause Java by default can't do this.

    Although that may change with Java 9 but looking from the changes i haven't seen something for build in JSON Library . I heard but i haven't seen it inside.

    🌱

    You can see here all the new features of Java 9.

    You will find what libraries you may need , along with tutorials here

    🌱

    Until it exists we have the amazing Jackson Library:

    1.1 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);
    

    1.2 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);
    

    Where Staff is:

     import java.math.BigDecimal;    import java.util.List;
     public class Staff { 
         private String name; 
         private int age; 
         private String position; 
        private BigDecimal salary; 
        private List<String> skills; 
        //getters and setters 
    }
    

    Complete tutorial here