Search code examples
javaappendsubstringindexoflastindexof

Is there a better way to divide this string into substrings?


I am trying to extract the "first_name" and "last_name" from a long string of information that look like this:

{
    "123123123": {
        "id": "12321312****",
        "email": "***************",
        "first_name": "Marcus",
        "gender": "male",
        "last_name": "Bengtsson",
        "link": "https://www.facebook.com/app_scoped_user_id/123123123/",
        "locale": "en_EN",
        "middle_name": "Peter",
        "name": "Marcus Peter Bengtsson"
    }
}

The way I do it (which is probably horribly wrong and a pretty bad solution) is that I firstly extract the substring from "first_name" to "link" with this code:

String subStr = str.substring(str.indexOf("first_name"), str.lastIndexOf("link"));

Then I get:

first_name":"Marcus","gender":"male","last_name":"Bengtsson","

Then I do the same thing but from ":" to "gender" to get the "first_name:

String firstNameOfUser = subStr.substring(subStr.indexOf(":")+2, subStr.lastIndexOf("gender")-3);

Then the same thing for "last_name":

String lastNameOfUser = subStr.substring(subStr.indexOf(""last_name"")+12, subStr.lastIndexOf(",")-1);

And lastly I append the both strings with a space in between:

String nameOfUser = new StringBuilder().append(firstNameOfUser).append(" ").append(lastNameOfUser).toString();

And then I get:

Marcus Bengtsson

There is probably a much better way to do this but I can't seam to figure out how.


Solution

  • This looks like a JSON so it would be much better to parse it as such using one of many available parsers and then extract the data.