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
  • It looks like what you're really trying to do is parse JSON. If that's the case, use a JSON parser. Commented Nov 4, 2019 at 5:58
  • 1
    Possible duplicate of string to string array conversion in java Commented Nov 4, 2019 at 6:07
  • What is the different between array type string and string array? Commented Nov 4, 2019 at 6:16
  • can't you publish/receive the array itself? Commented Nov 4, 2019 at 6:23
  • No, i can not. In kafka producer there is no string array type messages Commented Nov 4, 2019 at 6:25

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());
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.