Search code examples
pythonjavaserial-port

Java - Converting byte array to a python dictionary-like object


I'm trying to migrate an application from Python to Java, which I'm a complete noob, but I have encountered a problem.

In python I receive bytes through the serial ports and I'm able to split the data in a single line by doing just like so:

temp = temp.decode("utf-8").split(',')

Example data:

S,24,31479873,00000,00000,00000,3296,

So it'd be divided to a list of elements, like so:

['S', '24', '31479873', '00000', '00000', '00000', '3296', '\r\n']

And I'd be able to loop through a key list and relate that list to this split list. Appending the result to a list of dictionaries called "packages".

key = ["type", "line_number", "timestamp", "hits", "pulses", "hits_acc", "voltage", "unused"]
self.packages.append({key[i]:temp[i] for i in range(len(key))})

I want the exact same functionality in Java. Can anyone guide me through this? Sorry if I'm being too vague but I'm a complete beginner when it comes to Java.


Solution

  • Java is strong typed language , so the code may seems a little complex, as follows:

    String line = "S,24,31479873,00000,00000,00000,3296,x";
            String [] parts = line.split(",");
            String [] cols = {"type", "line_number", "timestamp", "hits", "pulses", "hits_acc", "voltage", "unused"};
            if (parts.length != cols.length) {
                System.out.println("Data invalid");
                System.exit(-1);
            }
            Map<String, String> result = new HashMap<>();
            for (int i = 0; i < cols.length; i++) {
                String key = cols[i];
                String val = parts[i];
                result.put(key, val);
            }