You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中移除TCP传输的压力传感器消息冗余部分并提取JSON数据

Extract JSON from TCP Message with Redundant HTTP Headers (Java Implementation)

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:

  1. 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.
  2. 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("&quot;", "\"");
    }

    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{ &quot;device&quot;: &quot;0305170025&quot;, &quot;Business&quot;: &quot;0305170025&quot;, &quot;version&quot;: &quot;V1.0&quot;, &quot;session&quot;: 1631171130, &quot;command&quot;: &quot;send_server_measure&quot;, &quot;content&quot;: { &quot;measure&quot;: [ { &quot;name&quot;: &quot;press&quot;, &quot;datatype&quot;: &quot;float&quot;, &quot;content&quot;: [ { &quot;t&quot;: 1631169540, &quot;v&quot;: 9901 }, { &quot;t&quot;: 1631169550, &quot;v&quot;: 9901 }, { &quot;t&quot;: 1631169560, &quot;v&quot;: 9901 }, { &quot;t&quot;: 1631171130, &quot;v&quot;: 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 10:52:53