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?

5

3 Answers 3

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());
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>>(){});
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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.