1

Let's consider the following object:

public class MyObject{
    int a, b;

    public MyObject(){
        setA(1);
        setB(1);
    }

    // getters and setters

}

I have the following string

{"a":4}

when I use Jackson 2 to create a new object I have a = 4 and b = 1 (I assume, it's the object created with the empty constructor where setters are used to modify the fields that Jackson 2 reads in the string).

Now, I have an instance of myObject with a = 1 and b = 2 (different from the one I can have with the empty constructor). How can I use the String to "complete" the object to a = 4 and b = 2? In other words: how can I use an incomplete json string to replace field values in an already existing object different from the one created with the empty constructor?

EDIT: a possible solution from answer.

public static Object updateObject(String fileName, Object oldValue){
    try {
        return new ObjectMapper().readerForUpdating(oldValue).readValue(new File(fileName));
    } catch (IOException e) {
        e.printStackTrace();
        return oldValue;
    }
}

1 Answer 1

1

It's possible to deserialize into already existing object. In that way your constructor will be called only once.

See documentation on ObjectMapper.readerForUpdating . This question may also help.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.