package Mqttmessage.Util;
|
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
import Mqttmessage.Entity.GPSData;
|
import Mqttmessage.Entity.ResponseData;
|
|
/**
|
* 设备消息解析工具类 - 支持GPS数据、状态数据和响应数据的解析
|
*/
|
public class DeviceMessageParser {
|
|
private static final ObjectMapper objectMapper = new ObjectMapper();
|
|
static {
|
// 配置ObjectMapper
|
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
}
|
|
|
/**
|
* 解析为GPS数据对象(支持新协议格式,包含GPS、IMU和状态数据)
|
* @param jsonStr JSON字符串
|
* @return GPSData对象
|
* @throws JsonProcessingException 解析异常
|
*/
|
public static GPSData parseGPSData(String jsonStr) throws JsonProcessingException {
|
GPSData gpsData = objectMapper.readValue(jsonStr, GPSData.class);
|
|
// 可选:解析GGA数据
|
/* if (gpsData.getGps_raw() != null && gpsData.getGps_raw().startsWith("$GNGGA")) {
|
GPSData.GGAData ggaData = parseGGA(gpsData.getGps_raw());
|
gpsData.setGgaData(ggaData);
|
}*/
|
|
return gpsData;
|
}
|
|
|
|
/**
|
* 解析为响应数据对象
|
* @param jsonStr JSON字符串
|
* @return ResponseData对象
|
* @throws JsonProcessingException 解析异常
|
*/
|
public static ResponseData parseResponseData(String jsonStr) throws JsonProcessingException {
|
return objectMapper.readValue(jsonStr, ResponseData.class);
|
}
|
|
|
|
/**
|
* 将消息对象转换为JSON字符串
|
* @param message 消息对象(GPSData、StatusData或ResponseData)
|
* @return JSON字符串
|
* @throws JsonProcessingException 转换异常
|
*/
|
public static String toJson(Object message) throws JsonProcessingException {
|
return objectMapper.writeValueAsString(message);
|
}
|
|
/**
|
* 获取ObjectMapper实例(用于高级操作)
|
* @return ObjectMapper实例
|
*/
|
public static ObjectMapper getObjectMapper() {
|
return objectMapper;
|
}
|
|
/**
|
* 消息类型枚举
|
*/
|
public enum MessageType {
|
GPS("gps"),
|
STATUS("status"),
|
RESPONSE("response");
|
|
private final String type;
|
|
MessageType(String type) {
|
this.type = type;
|
}
|
|
public String getType() {
|
return type;
|
}
|
|
public static MessageType fromString(String type) {
|
for (MessageType mt : MessageType.values()) {
|
if (mt.type.equalsIgnoreCase(type)) {
|
return mt;
|
}
|
}
|
throw new IllegalArgumentException("未知的消息类型: " + type);
|
}
|
}
|
}
|