Search code examples
javajsonpojo

Creating a new Java object automatically with correct data values


I'm wondering is there anyway in Java to create an object from a simple POJO automatically with correct data values?

Lets say i have a simple POJO like this:

public class POJO {

    private int intVar;
    private boolean booleanVar;
    private String stringVar;

    public POJO(int intVar, boolean booleanVar, String stringVar) {
        this.intVar = intVar;
        this.booleanVar = booleanVar;
        this.stringVar = stringVar;     
    }

    //Geteru & Setteru...   
}

So basically I want to know can i create an object from this class with some sorta method or something that would read the variables and their types and assign them with ANY values but the value would be correct for the variable data type. For example intVar should get ofcourse an integer and stringVar should get a String etc.

This does not have to be the way to do this, what I am actually trying to achieve is im trying to automatically create a JSON of these POJO's I have, but the thing is i need some values for the JSON. I have already used gson for creating JSON's of my POJO's but i have no clue how can i automatically assign "correct" values for the variables. It doesn't have to happen by creating the new object, all I need is to get a JSON with variable values created from ANY POJO like this.

For example:

{
     intVar=1,
     booleanVar=true,
     stringVar="my string"
}

The reason I am asking can I automatically create a new object with correct values for variable from a simple POJO like this, is that i would then be able to create the satisfying JSON from it, but if anyone know any alternate solutions for getting the values to the JSON, feel free to suggest them :).


Solution

  • From my opinion you need to try jackson or GSON libraries. From my experience, jackson better.

    I can't write 100% working way for implementation, because in my experience I never do same things. I always convert JSON formatted data into known class (it come to me as mapped object as argument in spring controller). Have no idea, why you need to map abstract class, possibly it is wrong design, possibly not.

    Using jackson you will be able to use inheritance: http://www.baeldung.com/jackson-inheritance, but I never try it before.

    If it will not satisfy your needs, you may use this:

    Class[] candidates = new Class[]{InheritedClass1.class, InheritedClass2.class, InheritedClass3.class};
    ObjectMapper mapper = new ObjectMapper();
    String jsonInString = "{\"your\":\"json\"}";
    AbstractClass instance = null;
    for(Class clazz : candidates) {
        try{
            instance = mapper.readValue(jsonInString, clazz);
        } catch (Exception e){
        }
        if(instance !== null) {
            break;
        }
    }
    System.out.println(instance);