Home  >  Article  >  Automatically convert POJO to JSON using Jackson

Automatically convert POJO to JSON using Jackson

王林
王林forward
2024-02-09 12:24:19677browse

In modern Web development, front-end and back-end data interaction is a very important link. In Java development, converting POJO objects into JSON format data is a common requirement. To simplify the development process, Jackson has become a common solution. Jackson is a powerful Java library that provides automatic conversion of POJO objects into JSON format. This article will describe how to use Jackson to achieve this goal. Let us take a look at the detailed guide prepared by PHP editor Yuzai for you!

Question content

I hope to be able to do this:

system.out.printf("my obj: %s\n", myobject);

And let it generate json. My best solution so far is to do this:

@Override
public String toString() {
    ObjectMapper mapper = new ObjectMapper();
    String retVal = null;
    try {
        retVal = mapper.writeValueAsString(this);
    }
    catch (JsonProcessingException ignored) {
    }
    return retVal;
}

This does work, but it's annoying to have to do this on every single one of my pojos. Is there an annotation I can use, or some other way to automate this. I'm using jackson and project lombok.

I tried to implement it only in the base class, but it won't work in subclasses. If I implement it throughout the chain it does work.

Workaround

If you have complex inherited classes, you should remove all @tostring, @data (which contain @ tostring ) or any override of a subclass's tostring.

This is an example of all the properties used in the tostostostostostostring method:

my obj: {"superproperty":"super","name":"abc","number":15,"gender":true}
public abstract class BaseObject {
  @Override
  public String toString() {
    ObjectMapper mapper = new ObjectMapper();
    String retVal = null;
    try {
      retVal = mapper.writeValueAsString(this);
    } catch (JsonProcessingException ignored) {
    }
    return retVal;
  }

  @Setter
  @Getter
  @AllArgsConstructor
  public static class ChildObject extends BaseObject {
    private String superProperty;
  }

  @Setter
  @Getter
  public static class ChildObject1 extends ChildObject {
    private String name;
    private int number;
    private boolean gender;

    public ChildObject1(String superProperty, String name, int number, boolean gender) {
      super(superProperty);
      this.name = name;
      this.number = number;
      this.gender = gender;
    }
  }

  public static void main(String[] args) {
    System.out.printf("My obj: %s\n", new ChildObject1("super","abc", 15, true));
  }
}

The above is the detailed content of Automatically convert POJO to JSON using Jackson. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete