如何在Java中移除TCP传输的压力传感器消息冗余部分并提取JSON数据
Got it, let's break down how to solve this problem—you need to strip out the redundant HTTP request headers from your TCP-received message and extract only the JSON sensor data. Here's a step-by-step solution with code examples:
Approach
The key here is to separate the HTTP header noise from the JSON payload. We have two reliable ways to do this, depending on how your message is formatted:
- Use HTTP Protocol Separator: Standard POST requests separate headers from the body with a blank line (
\r\n\r\n). This is the most accurate method if your message follows HTTP specs. - Locate JSON Boundaries: If the header and JSON are directly concatenated without the standard separator, we can find the first
{and last}to extract the full JSON block (since JSON is always wrapped in outer curly braces).
We'll also need to handle the HTML-escaped double quotes (") in your JSON data—replace them with regular double quotes so JSON parsers can read the data correctly.
Java Code Implementation
Step 1: Extract and Clean the JSON String
import java.util.regex.Matcher; import java.util.regex.Pattern; public class SensorMessageParser { public static String extractAndCleanJson(String rawTcpMessage) { String jsonContent = null; // First, try using the standard HTTP header-body separator (\r\n\r\n) String httpSeparator = "\r\n\r\n"; int separatorIndex = rawTcpMessage.indexOf(httpSeparator); if (separatorIndex != -1) { jsonContent = rawTcpMessage.substring(separatorIndex + httpSeparator.length()); } else { // Fallback: Find the first { and last } to capture the full JSON block int startJson = rawTcpMessage.indexOf("{"); int endJson = rawTcpMessage.lastIndexOf("}"); if (startJson != -1 && endJson != -1 && startJson < endJson) { jsonContent = rawTcpMessage.substring(startJson, endJson + 1); } else { throw new IllegalArgumentException("Invalid message: No valid JSON payload found"); } } // Replace HTML-escaped quotes with regular double quotes return jsonContent.replaceAll(""", "\""); } public static void main(String[] args) { // Example raw message from your sensor String rawMessage = "POST /V1.0/data.aspx HTTP/1.1 Host: 124.43.5.212 User-Agent: RT-Thread HTTP Agent Connection: Keep-Alive Content-Length: 4349{ "device": "0305170025", "Business": "0305170025", "version": "V1.0", "session": 1631171130, "command": "send_server_measure", "content": { "measure": [ { "name": "press", "datatype": "float", "content": [ { "t": 1631169540, "v": 9901 }, { "t": 1631169550, "v": 9901 }, { "t": 1631169560, "v": 9901 }, { "t": 1631171130, "v": 9901 } ] } ] } }"; try { String cleanedJson = extractAndCleanJson(rawMessage); System.out.println("Extracted and cleaned JSON:\n" + cleanedJson); // Now you can parse this JSON into a Java object } catch (IllegalArgumentException e) { System.err.println("Error parsing message: " + e.getMessage()); } } }
Step 2: Parse the Cleaned JSON into a Java Object
Once you have the cleaned JSON, use a library like Jackson or Gson to convert it into a strongly-typed Java object for easier processing. Here's an example with Jackson:
First, add the Jackson dependency to your pom.xml (Maven) or build.gradle (Gradle):
<!-- Maven --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency>
Then create the corresponding model classes:
import java.util.List; public class SensorData { private String device; private String Business; private String version; private long session; private String command; private Content content; // Getters and Setters public String getDevice() { return device; } public void setDevice(String device) { this.device = device; } public String getBusiness() { return Business; } public void setBusiness(String business) { Business = business; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public long getSession() { return session; } public void setSession(long session) { this.session = session; } public String getCommand() { return command; } public void setCommand(String command) { this.command = command; } public Content getContent() { return content; } public void setContent(Content content) { this.content = content; } public static class Content { private List<Measure> measure; // Getters and Setters public List<Measure> getMeasure() { return measure; } public void setMeasure(List<Measure> measure) { this.measure = measure; } public static class Measure { private String name; private String datatype; private List<DataPoint> content; // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDatatype() { return datatype; } public void setDatatype(String datatype) { this.datatype = datatype; } public List<DataPoint> getContent() { return content; } public void setContent(List<DataPoint> content) { this.content = content; } public static class DataPoint { private long t; private int v; // Getters and Setters public long getT() { return t; } public void setT(long t) { this.t = t; } public int getV() { return v; } public void setV(int v) { this.v = v; } } } } }
Now parse the JSON into the model:
import com.fasterxml.jackson.databind.ObjectMapper; public class JsonParser { public static void main(String[] args) { String cleanedJson = // The cleaned JSON from extractAndCleanJson() ObjectMapper objectMapper = new ObjectMapper(); try { SensorData sensorData = objectMapper.readValue(cleanedJson, SensorData.class); // Access the sensor data System.out.println("Device ID: " + sensorData.getDevice()); System.out.println("First pressure reading: " + sensorData.getContent().getMeasure().get(0).getContent().get(0).getV()); } catch (Exception e) { e.printStackTrace(); } } }
Notes
- Always prefer the HTTP separator method if possible—it's more reliable for messages that follow HTTP standards.
- The fallback method using
{and}works if the header doesn't contain any curly braces (which is true for standard HTTP headers). - Make sure to handle exceptions appropriately (e.g., invalid message formats, JSON parsing errors) in your production code.
内容的提问来源于stack exchange,提问作者Yushantha chathuranga

