0

I have a String in a following format:

 {"id":"1263e246711d665a1fc48f09","facebook_username":"","google_username":"814234576543213456788"}

but sometimes this string looks like:

{"id":"1263e246711d665a1fc48f09","facebook_username":"109774662140688764736","google_username":""}

How can I extract those values if I do not know the index of substrings as they will change for different cases?

2
  • 8
    This is a JSON String. Instead of parsing it, find a JSON library that will generate a JSONObject from this string. If you are using Java EE 7 and higher, you can look at the JSON-P framework. Commented Apr 10, 2016 at 21:08
  • I solved this problem in really easy way altough I belive that GaruGaru's answer is correct. ` json = new JSONObject(JsonResponse); String myID = json.getString("id"); String googleUserName = json.getString("google_username");` Commented Apr 11, 2016 at 13:41

3 Answers 3

3

That looks like json format, you should give a look to the Gson library by google that will parse that string automatically.

Your class should look like this

public class Data
{
private String id;

private String facebook_username;

private String google_username;
// getters / setters...
}

And then you can simply create a function that create the object from the json string:

Data getDataFromJson(String json){
     return (Data) new Gson().fromJson(json, Data.class);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice answer, Welcome to stackoverflow!
1

That String is formated in JSON (JavaScript Object Notation). Is a common language used to transfer data.

You can parse it using Google's library Gson, just add it to your class path .

    Gson gson = new Gson();
    //convert the json string back to object
    DataObject obj = gson.fromJson(br, DataObject.class); //The object you want to convert to.

https://github.com/google/gson

Check this out on how to convert to Java Object

Comments

0

Parsing as JSON notwithstanding, here's a pure string-based solution:

String id = str.replaceAll(".*\"id\":\"(.*?)\".*", "$1");

And similar for the other two, swapping id for the other field names.

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.