package com.persagy.bdtp.adm.datatx;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.persagy.bdtp.adm.entity.db.AdmObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 针对数据传输的ObjectMapper，过滤字段
 */
@Component
public class ObjectMapper4Tx {

	private final ObjectMapper objectMapper;

	private ObjectMapper mapper;

	@Autowired
	public ObjectMapper4Tx(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
		configCommonMapper();

		this.mapper = new ObjectMapper();
		configMapper();
	}

	private void configCommonMapper(){
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}

	private void configMapper(){
		mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

		//设置实体的传输字段
		mapper.addMixIn(AdmObject.class, ObjectForTx.class);

	}

	public ObjectMapper mapper() {
		return mapper;
	}

	public String toJson(Object obj){
		try{
			return mapper.writeValueAsString(obj);
		}catch (JsonProcessingException e){
			throw new RuntimeException(e);
		}
	}

}
