0

I use apache kafka to publish the string message. Before publishing, message type is string array like below,

String[] msgArray = ["aaa", "bbb", "ccc"];

My kafka publishing message type is java string, so I convert this array to string with Arrays.toString(msgArray) method. Apache Kafka publishing and consuming work well. The received message is Java String,["aaa", "bbb", "ccc"]. But the problem is I have no idea how to convert this array type string message back to string array. Below is the part of my codes.

//record.value is array type string -> ["aaa", "bbb", "ccc"]
String[] parameters = new String[record.value().split(",").length];  
int i=0;
for(String str : record.value().split(",")) {
    if(i < parameters.length) {
        parameters[i] = str.replace("]", "").replace("[", "");
    }
    i++;
}

But the result is not appropriate. Are there any arrays api which converts array type string to string array?

Joseph Hwang
  • 1,337
  • 3
  • 38
  • 67

3 Answers3

3

How about deserializing the String with JSONArray:

import org.json.JSONArray;

String[] msgArray = {"aaa", "bbb", "ccc"};

// serializing
String msg = Arrays.toString(msgArray);

// deserializing
JSONArray jsonArray = new JSONArray(msg);
System.out.println(jsonArray.toList());
Psidom
  • 209,562
  • 33
  • 339
  • 356
0

You can follow Psidom's answer or try this option:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;    
List<String> msgArray = new ObjectMapper().readValue(msg, new TypeReference<List<String>>(){});
Nikhil
  • 1,126
  • 12
  • 26
0

You can also use Object Mapper for serializing and deserializing your input and output. As it provide support of all of the data types as well as custom.

String[] msgArray = {"aaa", "bbb", "ccc"};

ObjectMapper objectMapper = new ObjectMapper();
String value = objectMapper.writeValueAsString(msgArray);
String[] strings = objectMapper.readValue(value, String[].class);
Garvit Khamesra
  • 375
  • 2
  • 9