package com.xydl.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.sql.Timestamp; import java.util.*; import java.util.stream.Collectors; public class FormatUtil { public static String mqttFormatTransform(List> list, Map fieldMap){ ObjectMapper objectMapper = new ObjectMapper(); Map resultMap = new HashMap(){{ put("AssetList",list.stream().map(e -> recordTransform(e,fieldMap)).collect(Collectors.toList())); }}; String jsonString = null; try { jsonString = objectMapper.writeValueAsString(resultMap); } catch (JsonProcessingException e) { throw new RuntimeException(e); } return jsonString; } public static Map recordTransform(Map record, Map fieldMap){ Map mqttRecord = new TreeMap<>(); List> attribuiteList = new ArrayList<>(); for(String key : record.keySet()){ if(fieldMap.containsKey(key)){ attribuiteList.add(new HashMap(){{ put("AttributeCode", fieldMap.get(key)); put("DataValue",record.get(key)); }}); } } mqttRecord.put("AssetCode",record.get("sensorid")); mqttRecord.put("AttributeList",attribuiteList); String captureTime = record.get("d_time") !=null ? (String) record.get("d_time") : (String) record.get("capturetime"); mqttRecord.put("Timestamp",Timestamp.valueOf(captureTime).getTime()); return mqttRecord; } // private static List> transformFieldForList(Map fieldMap, List> oriFieldList) { // List> newDeviceIDData = new ArrayList<>(); // for(Map fieldValueMap : oriFieldList){ // newDeviceIDData.add(transformOneRecord(fieldMap,fieldValueMap)); // } // return newDeviceIDData; // } // // private static Map transformOneRecord(Map fieldMap, Map fieldValueMap) { // Map newFieldValueMap = new HashMap<>(); // for(String field : fieldMap.keySet()){ // if(fieldValueMap.containsKey(field)){ // newFieldValueMap.put(fieldMap.get(field),fieldValueMap.get(field) ); // } // } // return newFieldValueMap; // } // public static void main(String[] args) { // System.out.println(Timestamp.valueOf("2022-05-01 12:11:00").getTime()); // System.out.println(new Timestamp(new Date(Timestamp.valueOf("2022-05-01 12:11:00").getTime()).getTime())); // } }