如何在fastxml中实现自定义序列化功能

时间:2014-12-03 18:46:21

标签: java json serialization jackson fasterxml

我的JSON:

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

如果street为null,使用JsonSerialize.Inclusion.NON_NULL,我可以获得..

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

但是我希望得到这样的东西..(当地址不为空时,它是一个新的/空对象。但是街道是空的。)

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

我认为有自定义序列化功能,如JsonSerialize.Inclusion.VALID_OBJECT。 在Address类中添加isValid()方法然后如果返回true则序列化,否则不要序列化。

但我不知道如何进一步/哪个类要覆盖。这是可能的还是其他任何观点?请建议。


添加了课程

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;
}
}

注意:我现在不担心反序列化。即丢失地址对象。

提前致谢。

2 个答案:

答案 0 :(得分:1)

使用序列化的自定义JSON对象非常简单。

我在我的项目中写了一个claas我给你一个如何在项目中实现它的线索

  

贷款申请(POJO类)

 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;

现在包含使用序列化逻辑的自定义的LoanApplicationSerializer类................

    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..

答案 1 :(得分:0)

您可以使用@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

为您的班级添加注释

示例:

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

您可以在Jackson faster xml

找到一些有用的信息