Should serialization logic be in the entity or other class

后端 未结 2 1291
长情又很酷
长情又很酷 2021-01-19 00:16

Where should object serialization logic (the mapping of fields into XML or JSON names and values) be placed? Inside each entity object OR into a different set of classes onl

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-19 00:37

    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

    Application (POJO Class)

     import java.io.Serializable;
     import java.util.List;
     import org.webservice.business.serializer.ApplicationSerializer;
     import com.fasterxml.jackson.databind.annotation.JsonSerialize; 
    
    @JsonSerialize(using=ApplicationSerializer.class)
      public class Application  implements Serializable {
    
    private static final long serialVersionUID = 1L;
    private double amount;
    private String businessType;
    private String currency;
    private int duration;
    }
    

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

     package org.webservice.business.serializer;
    
      import java.io.IOException;
      import org.webservice.business.dto.Application;
      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 ApplicationSerializer extends JsonSerializer {
    
    @Override
    public void serialize(Application prm_objObjectToSerialize, JsonGenerator prm_objJsonGenerator, SerializerProvider prm_objSerializerProvider) throws IOException, JsonProcessingException {
        if (null == prm_objObjectToSerialize) {
        } else {
            try {
                prm_objJsonGenerator.writeStartObject();
    
                prm_objJsonGenerator.writeNumberField("amount", prm_objObjectToSerialize.getAmount());               
                prm_objJsonGenerator.writeNumberField("duration", prm_objObjectToSerialize.getDuration());
                prm_objJsonGenerator.writeStringField("businesstype", prm_objObjectToSerialize.getBusinessType());
                prm_objJsonGenerator.writeStringField("currency", prm_objObjectToSerialize.getCurrency());
    
    
            } catch (Exception v_exException) {
                v_exException.printStackTrace()
            } finally {
                prm_objJsonGenerator.writeEndObject();
            }
        }
      }
    

提交回复
热议问题