Reputation: 1583
I am creating an android application. I have multiple strings, one of which is
[
{
"name": "lofer",
"fbname": "\u200b \u179c",
"link": "http:\/\/example.com:9874\/et\/oyp.pls",
"0": null
},
{
"name": "oxypo",
"fbname": "\u200b \u179c\u17b7",
"link": "http:\/\/example.com:9874\/et\/pou.pls",
"0": null
}
]
This is stored in String result
Now I want to extract from this string is the names and respective links like
Name1= lofer
Link1= http://example.com:9874/et/oyp.pls
Name2= oxypo
Link2= http://example.com:9874/et/pou.pls
First I am removing all the double quotes then I remove "[" from the start and "]" from the end and then I split by "}" then I am removing "{" and then splitting each by "," and then I find name and link.
I have written a code and its working perfectly fine, I am getting what I want but I want to optimize it. Here is my code and what I am doing
result=result.replace("\"","");
result=result.substring(1,result.length()-1);
String [] split=result.split("\\}");
for(int i=0;i<split.length;i++)
{
split[i]=split[i].substring(1);
String [] spl=split[i].split(",");
Data d = new Data();
for(int j=0;j<spl.length;j++)
{
if(spl[j].substring(0,4).equals("name"))
{
d.name=spl[j].substring(5);
}
else if(spl[j].substring(0,4).equals("link"))
{
d.link=spl[j].substring(5);
d.link=d.link.replace("\\", "");
}
}
output.add(d);
Log.i("name",d.name);
Log.i("link",d.link);
}
I am not good at regular expressions and maybe we can achieve all this with regular expression or with anything but OPTIMIZATION is my main concern here instead of replacing multiple times. Your help will be much appreciated.
Thanks
Upvotes: 0
Views: 107
Reputation: 76888
That's JSON.
Android comes with basic JSON parsing classes and there are other libraries available (e.g. Gson, Jackson) that offer greater feature sets.
The most basic solution to your problem using the classes provided with Android is:
// Your JSON represents an array of objects
JSONArray jsonArray= new JSONArray(yourString);
// Now you have the array, iterate and get the objects
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
System.out.println("Name" + i + "= " + obj.getString("name"));
System.out.println("Link" + i + "= " + obj.getString("link"));
}
Upvotes: 4