spring Practice--Handling Serialization and Deserialization of Amounts in spring

1. Concepts

Serialization of java objects means that the state of the object is converted into a byte stream that can be used later to regenerate the object in the same state.Object serialization is an implementation of object persistence, which converts object properties and methods into a serialized form for storage and transmission.Deserialization is the process of rebuilding objects from these stored information.

Serialization: The process of converting a java object into a sequence of bytes.

Deserialization: The process of converting a sequence of bytes into a java object.(

2. Why serialization and deserialization

We know that when two processes communicate remotely, they can send each other various types of data, including text, pictures, audio, video, and so on, which are transmitted over the network in a binary sequence.So when two Java processes communicate, can they transfer objects between them?The answer is yes.How can I do that?This requires Java serialization and deserialization.In other words, on the one hand, the sender needs to convert the Java object into a sequence of bytes, then transfer it over the network; on the other hand, the receiver needs to recover the Java object from the sequence of bytes.When we understand why Java serialization and deserialization are needed, we naturally think about the benefits of Java serialization.One advantage is data persistence, which allows data to be permanently saved to the hard disk (usually in a file) through serialization, and the other is remote communication through serialization, which is the byte sequence of objects being transmitted over the network.(

3. The Java API involved

java.io.ObjectOutputStream represents the object output stream, and its writeObject(Object obj) method serializes the obj object specified by the parameter to write the resulting byte sequence to a target output stream.

java.io.ObjectInputStream represents an object input stream whose readObject() method source input stream reads a sequence of bytes, deserializes them into an object, and returns them.

Only objects of classes that implement the Serializable or Externalizable interfaces can be serialized, otherwise an exception is thrown.(

Example use:

@JsonComponent
public class UserJsonSerializer extends JsonSerializer<User> {

    @Override
    public void serialize(User user, JsonGenerator jsonGenerator, 
      SerializerProvider serializerProvider) throws IOException, 
      JsonProcessingException {

        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField(
          "favoriteColor", 
          getColorAsWebColor(user.getFavoriteColor()));
        jsonGenerator.writeEndObject();
    }

    private static String getColorAsWebColor(Color color) {
        int r = (int) Math.round(color.getRed() * 255.0);
        int g = (int) Math.round(color.getGreen() * 255.0);
        int b = (int) Math.round(color.getBlue() * 255.0);
        return String.format("#%02x%02x%02x", r, g, b);
    }

 

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Objects;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
 
/**
 * <p>Entry retains two decimal places </p>
 * @author wanghuihui Create on 2019 February 24, 2000
 * @version 1.0
 */
public class SerializerBigDecimal extends JsonSerializer<BigDecimal> {
	final DecimalFormat myFormatter = new DecimalFormat("#.00"); 
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if(Objects.isNull(value)) {
            gen.writeNumber("0.00");
        } else {
            // HALF_UP: Rounding
        	//String val = value.setScale(2, RoundingMode.HALF_UP).toString();
        	//String val = myFormatter.format(value);
        	//Test printing is okay, back to front or something wrong
        	//System.out.println(val);
            //gen.writeNumber(val);
            //Method 2: This works
            serializers.defaultSerializeValue(myFormatter.format(value), gen);
        }
    }
}

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Objects;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
 
/**
 * <p>Arguments keep two decimal places </p>
 * @author wanghuihui Create on 2019 February 24, 2000
 * @version 1.0
 */
public class DeserializerBigDecimal extends JsonDeserializer<String> {
	final DecimalFormat myFormatter = new DecimalFormat("#.00"); 
    /**
     * Argument Keep Two Decimal Digits
     * @param jsonParser
     * @param deserializationContext
     * @return
     * @throws IOException
     */
    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        if (Objects.isNull(jsonParser.getDecimalValue())) {
            return null;
        } else {
            // HALF_UP: Rounding
            // return jsonParser.getDecimalValue().setScale(2, RoundingMode.HALF_UP);
            return myFormatter.format(jsonParser.getDecimalValue());
        }
    }
}

public class xxxEntity implements Serializable, Cloneable
{
	@JsonDeserialize(using = DeserializerBigDecimal.class)
	@JsonSerialize(using = SerializerBigDecimal.class)
	private BigDecimal sumAmt;
}

Keywords: Programming Java network

Added by cougarreddy on Sat, 07 Mar 2020 18:29:12 +0200