Lostsoul
Lostsoul

Reputation: 26067

How can I convert a String back to a String[] if I used `Arrays.toString` to convert it like that in the first place?

I'm using a queue service that seems to only allow me to send a string as the message(sort of don't think thats right but haven't been able to prove otherwise), but I need 3 different data items to process my work(an int, double and int[]). So I take all three datatypes and convert them to a string using Arrays.toString.

My problem is once my worker processes get the message I need to convert them back. The worker sees this: [0, 43.0, [0, 59, 16]] but I'm not sure how to most efficiently convert it. The way I'm doing it right now is to remove the first and last characters and then doing a String[] temp = queue_string.split(","); to get it back as a list.

I'm fine if this way is the only way but I'm wondering if there's a cleaner way? just like the Arrays.toString is there something like a String.toArray(this doesn't exist, I tried already :-)

Upvotes: 0

Views: 126

Answers (1)

Jon Gauthier
Jon Gauthier

Reputation: 25592

I think it'd be best to use a standard like JSON as the format for data transported between processes. Data can easily be marshaled from a string to native data types and back in Java.

Gson gson = new Gson();

int[] sub = { 0, 59, 16 };
Object[] values = { 0, 43.0, sub };
String output = gson.toJson(values);       // => [0, 43.0,[0,59,16]]

Object[] deserialized = gson.fromJson(output, Object[].class);
for ( Object obj : deserialized ) {
    // => 0.0, 43.0, [0.0, 59.0, 16.0]
}

Upvotes: 4

Related Questions