How to implement customized serialization feature in fasterxml

醉酒当歌 提交于 2019-12-13 00:42:21

问题


My JSON:

{ "name": "asdf", "age": "15", "address": { "street": "asdf" } }

If street is null, with JsonSerialize.Inclusion.NON_NULL, I can get..

{ "name": "asdf", "age": "15", "address": {} }

But I want to get something like this.. (when address is not null, it is a new/empty object. But street is null.)

{ "name": "asdf", "age": "15" }

I thought to have custom serialization feature like JsonSerialize.Inclusion.VALID_OBJECT. Adding isValid() method in the Address class then if that returns true serialize else don't serialize.

But I don't know how to proceed further/which class to override. Is this possible or any other views on this? Please suggest.


Added classes

public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();
    Customer customer = new Customer();
    customer.setName("name");
    customer.setAddress(new Address());
    mapper.writeValue(new File("d:\\customer.json"), customer);
}

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Customer {

private String name;
private Address address;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Address getAddress() {
    return address;
}
public void setAddress(Address address) {
    this.address = address;
}
}

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Address {

private String street;

public String getStreet() {
    return street;
}
public void setStreet(String street) {
    this.street = street;
}
}

Note: I am not worrying about deserialization now. i.e, loss of address object.

Thanks in advance.


回答1:


Customized JSON Object using Serialization is Very Simple.

I have wrote a claas in my project i am giving u a clue that how to Implement this in Projects

Loan Application (POJO Class)

 import java.io.Serializable;
 import java.util.List;
 import org.webservice.business.serializer.LoanApplicationSerializer;
 import com.fasterxml.jackson.databind.annotation.JsonSerialize;


  @JsonSerialize(using=LoanApplicationSerializer.class)
  public class LoanApplication  implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private double amount;
private User borrowerId;
private String businessType;
private String currency;
private int duration;
private Date lastChangeDate;
private long loanApplicationId;
private String myStory;
private String productCategory;
private String purpose;
private Date startDate;
private String status;
private String type;
private String salesRepresentative;

Now LoanApplicationSerializer class that contains the Customization using Serialization Logic................

    package org.ovamba.business.serializer;

  import java.io.IOException;
  import org.webservice.business.dto.LoanApplication;
  import com.fasterxml.jackson.core.JsonGenerator;
  import com.fasterxml.jackson.core.JsonProcessingException;
  import com.fasterxml.jackson.databind.JsonSerializer;
  import com.fasterxml.jackson.databind.SerializerProvider;

 public class LoanApplicationSerializer extends JsonSerializer<LoanApplication> {

@Override
public void serialize(LoanApplication prm_objObjectToSerialize, JsonGenerator prm_objJsonGenerator, SerializerProvider prm_objSerializerProvider) throws IOException, JsonProcessingException {
    if (null == prm_objObjectToSerialize) {
    } else {
        try {
            prm_objJsonGenerator.writeStartObject();
            prm_objJsonGenerator.writeNumberField("applicationId", prm_objObjectToSerialize.getLoanApplicationId());
            prm_objJsonGenerator.writeStringField("status", prm_objObjectToSerialize.getStatus());
            prm_objJsonGenerator.writeNumberField("amount", prm_objObjectToSerialize.getAmount());
            prm_objJsonGenerator.writeNumberField("startdate", prm_objObjectToSerialize.getStartDate().getTime());
            prm_objJsonGenerator.writeNumberField("duration", prm_objObjectToSerialize.getDuration());
            prm_objJsonGenerator.writeStringField("businesstype", prm_objObjectToSerialize.getBusinessType());
            prm_objJsonGenerator.writeStringField("currency", prm_objObjectToSerialize.getCurrency());
            prm_objJsonGenerator.writeStringField("productcategory", prm_objObjectToSerialize.getProductCategory());
            prm_objJsonGenerator.writeStringField("purpose", prm_objObjectToSerialize.getPurpose());
            prm_objJsonGenerator.writeStringField("mystory", prm_objObjectToSerialize.getMyStory());
            prm_objJsonGenerator.writeStringField("salesRepresentative", prm_objObjectToSerialize.getSalesRepresentative());
        } catch (Exception v_exException) {
            //ExceptionController.getInstance().error("Error while Serializing the Loan Application Object", v_exException);
        } finally {
            prm_objJsonGenerator.writeEndObject();
        }
    }
  }
}

Hope This may help u alot. Thanks..



回答2:


You can do it by annotating your class with @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

Example:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public myClass{
// attributes and accessors
}

You can find some useful informations at Jackson faster xml



来源:https://stackoverflow.com/questions/27279322/how-to-implement-customized-serialization-feature-in-fasterxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!