0

I am trying to split a string that looks like this:

{
"from": japan
"to": tokyo
},
{
"from": new york
"to": tokyo
},
{ 
 "id": 2509402760, 
 "date": "2016-04-16T00:00:00", 
}

I only want to print out "from and to". I am using substring to remove the ID and the Data.

The substring looks like this:

fullData.substring(fullData.indexOf("{"), (fullData.indexOf("}"));

The problem with this substring is that I only get the first "from and to", not the ones after which are new york and tokyo.

To solve this problem, I tried this substring:

fullData.substring(fullData.indexOf("{"), (fullData.indexOf("},{\"id"));

The problem with this one is that I am getting an "index of out bounds". I figured that the problem is that the string begins with a new line.

How can I make the indexof to match a new line, which begins with "id".

I cannot use replaceAll to replace all the lines. I want to substring it as it is. I hope you understand my problem, and I will gladly provide more data if needed.

Thank you.

1 Answers1

6

The best approach is to use a JSON parser for your data. If this is not an option, use the second overload of indexOf that lets you specify the lowest position where to start looking for substring:

int pos1 = fullData.indexOf("{");
int pos2 = fullData.indexOf("}", pos1);
String sub1 = fullData.substring(pos1, pos2);
int pos3 = fullData.indexOf("{", pos2);
int pos4 = fullData.indexOf("}", pos3);
String sub2 = fullData.substring(pos3, pos4);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523