Search code examples
javajacksontostringobjectmapperjackson-databind

Override toString of internal object


I have overridden toString() of an object called Skeleton, so when I call toString() the color variable is excluded.

public class Skeleton
{
    private List bones;
    private Color color;

    //  getters & setters

    @Override
    public String toString() 
    {
        String s = null;

        ObjectMapper mapper = new ObjectMapper();
        mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector(){
        @Override
        public boolean hasIgnoreMarker(final AnnotatedMember m) {
                List<String> exclusions = Arrays.asList("color");
                return exclusions.contains(m.getName())|| super.hasIgnoreMarker(m);
            }
        });

        try 
        {
            s = mapper.writeValueAsString(this);

        } catch (JsonProcessingException e) {

            e.printStackTrace();
        }

        return s;
    }
}

However, when I add a Skeleton object as a variable to an object called Body and call toString() on Body the color field of Skeleton is included.

public class Body
{
    private Skeleton skeleton = ....

Does anyone have any idea how to make Body use the overridden toString() method in Skeleton?


Solution

  • You have to override the toString() method of the Body class and include whatever details you deem necessary. Include the toString() method of the instance variable private Skeleton skeleton = ... and all other member variables that you may have in the Body class.