Should serialization logic be in the entity or other class

我的未来我决定 提交于 2019-12-20 02:57:09

问题


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 only concerned with serialization? Any other best practices out there that relate to this question?

For example:

class Person {
    String name;
}

Some people go about it this way:

class Person {
    String name;
    public String toJson () {
      // build JSON, use 'name' field
    }
}

But if we also needed toXML(), toCSV(), toXYZ() keeping that direction would create horribly polluted code and break the Single Responsibility Principle which is already broken even with a single toJson method, IMHO.

Another option and this is what I typically do:

interface Serializer {  public String toJson (); }

class PersonJsonSerializer implements Serializer {
    private Person p;
    public PersonJsonSerializer (Person p) { this.person = p; }
    public String toJson () {
      // build JSON, use p.name
    }
}

then a factory hands out Serializers depending on entity types:

class JsonSerializerFactory {
    public Serializer getSerializer (Object o) {
        if (o instanceof Person) {
            return new PersonJsonSerializer ((Person)o);
        }
        else if (o instanceof Account) {
            return new AccountJsonSerializer ((Account)o);
        }
        // ... etc
    }
}

There would also be XMLSerializerFactory, CSVSerializerFactory, and so forth.

However, most of the times people want to have full control over the serialization and would not buy into it and prefer to have toJson methods inside each class. They would claim is way simpler and less error prone.

What is the preferred way to go, and are there better alternatives to implement a solution to this problem?


回答1:


I would say the serialization logic should not be part of the POCO/data classes for many reasons:

  1. Single Responsibility Principle (data classes should only define data model, note serialization logic)
  2. There could be different kinds of serializers that you may require (json/xml etc. as you mentioned)
  3. Serialization implementation most of the time is a generic solution or an external package. Even if you want custom implementation for some objects, still you can have a generic solution which you can extend for specific classes, so no need to have it for each class.
  4. You can decorate your POCO classes with attributes to direct the serializer for special conditions (like to control sequence of properties, property names or even a customer serializer for complex type properties)

There will be other reasons as well but there are some strong arguments why you should not put the serialization logic into your POCO/Data Model.




回答2:


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<Application> {

@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();
        }
    }
  }


来源:https://stackoverflow.com/questions/35592831/should-serialization-logic-be-in-the-entity-or-other-class

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