There are multiple Java libraries available for serialization/deserialization. One of these is the excellent Jackson library where you can tune your serialization in a fine grained way.
If you own the source code of the POJO MyClass you can simply add some annotations to get it to work properly.
If you assume that MyCustomObject looks like this:
public class MyCustomObject {
private final String myVal;
public MyCustomObject(String myVal) {
this.myVal = myVal;
}
public String getMyVal() {
return myVal;
}
}
Then, your MyClass object can be declared like this (notice the annotations @JsonIgnore and @JsonProperty):
public class MyClass {
private Optional<MyCustomObject> object;
public MyClass(Optional<MyCustomObject> object) {
this.object = object;
}
// Ignore the "normal" serialization
@JsonIgnore
public Optional<MyCustomObject> getObject() {
return this.object;
}
public void setObject(Optional<MyCustomObject> object) {
this.object = object;
}
// This handles the serialization
@JsonProperty("object")
private MyCustomObject getObjectAndYesThisIsAPrivateMethod() {
return getObject().orElse(null);
}
}
Finally, you can use the following code for serializing to JSON:
ObjectMapper mapper = new ObjectMapper();
final String json = mapper.writeValueAsString(
new MyClass(Optional.ofNullable(new MyCustomObject("Yes, my value!"))));
The magic in the code above lies in the use of the ObjectMapper which handles the data binding i.e. converting between POJOs and JSON (and vice versa).
Another approach, if you do not own the source code of the MyClass class i.e. you can not modify it is to create a custom serializer as described in the Jackson docs.