场景:
- json大体格式一致,但是 ext_info 扩展字段对象,场景不同字段不同
- 根据某字段类型,不同值,对应不同实现的
Component
,处理不同场景- 这里根据
event
,来做不同处理
{"data": {"event": "eventWoMan","event_id": "123","ext_info": {"dist_sex": "女","dist_height": "162"},"target_name": "美女类型json"},"seq": 0
}{"data": {"event": "eventWoMan","event_id": "123","ext_info": {"dist_name": "小树","dist_age": "18"},"target_name": "帅哥类型json"},"seq": 0
}
接收类:
@lombok.Data
public class BusinessMsg<T> {private T data;private int seq;}
import com.fasterxml.jackson.annotation.JsonProperty;@lombok.Data
public class MsgData<T> {private String event;@JsonProperty("event_id")private String eventId;@JsonProperty("ext_info")private T extInfo;@JsonProperty("target_name")private String targetName;}
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;@Data
public class ExtInfoMan {/*** 目标姓名*/@JsonProperty("dist_name")private String distName;/*** 目标年龄*/@JsonProperty("dist_age")private String distAge;}
@Data
public class ExtInfoWoMan {/*** 目标性别*/@JsonProperty("dist_sex")private String distSex;/*** 目标高度*/@JsonProperty("dist_height")private String distHeight;}
处理service:
public interface JsonTService {/*** 预处理消息* @param businessMsg*/String handlerMsg(BusinessMsg<MsgData<JsonNode>> businessMsg);}
@Service("eventMan")
public class JsonManServiceImpl implements JsonTService {@Resourceprivate ObjectMapper objectMapper;@SneakyThrows@Overridepublic String handlerMsg(BusinessMsg<MsgData<JsonNode>> businessMsg) {JsonNode extInfo = businessMsg.getData().getExtInfo();ExtInfoMan exitInfo = objectMapper.treeToValue(extInfo, ExtInfoMan.class);return exitInfo.toString();}
}
@Service("eventWoMan")
public class JsonWoManServiceImpl implements JsonTService {@Resourceprivate ObjectMapper objectMapper;@SneakyThrows@Overridepublic String handlerMsg(BusinessMsg<MsgData<JsonNode>> businessMsg) {JsonNode extInfo = businessMsg.getData().getExtInfo();ExtInfoWoMan extInfoWoMan = objectMapper.treeToValue(extInfo, ExtInfoWoMan.class);return extInfoWoMan.toString();}
}
策略处理
import com.service.JsonTService;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;/*** @author xiaoshu*/
@Service
public class JsonStrategyContext {private final Map<String, JsonTService> orderStrategyMap = new ConcurrentHashMap<>();public JsonStrategyContext(Map<String, JsonTService> strategyMap) {this.orderStrategyMap.putAll(strategyMap);}public JsonTService getResource(String event){return orderStrategyMap.get(event);}
}
实际接口接收:
@Resourceprivate JsonStrategyContext jsonStrategyContext;@ApiOperation(value = "泛型处理,同格式json,扩展字段不一")@PostMapping("/revice")public String revice(@RequestBody BusinessMsg<MsgData<JsonNode>> businessMsg){String event = businessMsg.getData().getEvent();return jsonStrategyContext.getResource(event).handlerMsg(businessMsg);}