Lenny
Lenny

Reputation: 917

Java Parse String

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?

Upvotes: 0

Views: 119

Answers (3)

Bohemian
Bohemian

Reputation: 424953

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.

Upvotes: 0

No One
No One

Reputation: 704

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

Upvotes: 1

GaruGaru
GaruGaru

Reputation: 101

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);
}

Upvotes: 3

Related Questions