-1

I know its a common question, but I couldn't find information related to my contexts. First, I am building a String from JSon objects coming from different classes using Gson:

String myString= gson.toJson(obj);
String mystring1=gson.toJson(obj1);

...

then I am building a String which I want to deserialize latter on , I use:

String serializedString=myString.concat("|" +mystring1);

I use | because its not contained in any of the json objects, and I thought that I will I can then easily get an array of strings with: String [] arrayOfJsonStrings=serializedString.split("|"); gson.fromJson(arrayOfJsonStrings[0],obj.class); .....

the problem is that String [] arrayOfJsonStrings=serializedString.split("|"); is returning empty string, why ?Is there easy way to achieve that ?

user2557930
  • 319
  • 2
  • 11
  • 1
    Instead of this fragile, hacky solution, consider doing the safe, secure, simple and robust thing and encode the two strings in a JSON list instead. This will work no matter which characters each object contains. – that other guy Nov 01 '19 at 17:14

1 Answers1

-1

For one thing you are concatenating your strings two different ways. One of the following would be better and more consistent.

String serializedString=myString+"|"+mystring1;

or String serializedString=myString.concat("|").concat(myString1);

or String serializedString=String.format("%s|%s", myString, myString1)

Your problem is actually the fact that you are splitting on a regex reserved character. You need to escape the split with \ as mentioned here

serializedString.split("\\|");

But I don't really understand why you are doing this anyway? Why not initialize an array with those string values in it?

String myString= gson.toJson(obj);
String mystring1=gson.toJson(obj1);
String[] arrayOfJsonStrings = new String[]{myString, myString1};
Civerooni
  • 51
  • 8