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

如何在Java中实现Python串口字节数据转类字典对象的处理功能?

Java实现Python串口数据解码与字典映射功能

步骤拆解与代码实现

  1. 字节数据解码为字符串
    从串口读取到字节数组后,用UTF-8编码解码为字符串,对应Python的decode("utf-8"):

    import java.nio.charset.StandardCharsets;
    
    // 假设serialBytes是从串口读取到的字节数组
    String tempStr = new String(serialBytes, StandardCharsets.UTF_8);
    
  2. 分割字符串为数组
    使用逗号分割字符串,对应Python的split(','):

    String[] tempArray = tempStr.split(",");
    // 此时tempArray内容和Python分割后的列表一致:["S", "24", "31479873", "00000", "00000", "00000", "3296", "\r\n"]
    
  3. 定义key数组并映射为键值对
    Java中没有原生字典,用HashMap<String, String>模拟Python字典,再将字典存入List对应Python的packages列表:

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    // 定义key数组,和Python的key列表对应
    String[] keys = {"type", "line_number", "timestamp", "hits", "pulses", "hits_acc", "voltage", "unused"};
    
    // 初始化packages列表
    List<Map<String, String>> packages = new ArrayList<>();
    
    // 映射数组元素到字典
    Map<String, String> dataMap = new HashMap<>();
    // 循环遍历key和分割后的数组,避免数组越界
    for (int i = 0; i < keys.length && i < tempArray.length; i++) {
        dataMap.put(keys[i], tempArray[i]);
    }
    
    // 将字典添加到packages列表
    packages.add(dataMap);
    

完整示例代码

整合上述步骤,加入模拟串口数据(实际项目替换为真实串口读取逻辑):

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SerialDataProcessor {
    public static void main(String[] args) {
        // 模拟从串口读取的字节数据
        byte[] serialBytes = "S,24,31479873,00000,00000,00000,3296,\r\n".getBytes(StandardCharsets.UTF_8);

        // 解码字节为字符串
        String tempStr = new String(serialBytes, StandardCharsets.UTF_8);

        // 分割为数组
        String[] tempArray = tempStr.split(",");

        // 定义key数组
        String[] keys = {"type", "line_number", "timestamp", "hits", "pulses", "hits_acc", "voltage", "unused"};

        // 映射为字典并加入packages列表
        List<Map<String, String>> packages = new ArrayList<>();
        Map<String, String> dataMap = new HashMap<>();

        for (int i = 0; i < keys.length && i < tempArray.length; i++) {
            dataMap.put(keys[i], tempArray[i]);
        }

        packages.add(dataMap);

        // 打印结果验证
        for (Map<String, String> map : packages) {
            System.out.println(map);
        }
    }
}

注意事项

  • 实际串口读取需使用专用库(如jSerialComm)处理流数据,示例中用模拟数据替代。
  • 若需对数值类型字段(如line_number、voltage)计算,可将对应字符串转为int/long,比如Integer.parseInt(tempArray[1])。

内容的提问来源于stack exchange,提问作者Vinícius

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:45:37