Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Java Regex Match

I'm trying to pull out the strings:

 [{"name":"John Doe Jr."},{"name2":"John Doe"}] & {"name":"John Doe"} 

from the payload in the JSON strings below:

{"to":"broadcast", "type":"50", "payload":[{"name":"John Doe Jr."},{"name2":"John Doe"}]}

{"to":"broadcast", "type":"50", "payload":{"name":"John Doe"}}

use this regex code:

Pattern pattern = Pattern.compile("\\{(.*?)\"payload\":\"(.*?)\"\\}\\}");

Matcher matcher = pattern.matcher(jsonString);

I'm getting an IllegalStateException: No successfull match so far

What is wrong with my regular expression?

Also how to I get the number of matches it finds?

Any help would be appreciated.

like image 498
user268397 Avatar asked Aug 25 '12 16:08

user268397


1 Answers

This should work:

String someJson ="{\"to\":\"broadcast\", \"type\":\"50\", \"payload\":[{\"name\":\"John Doe Jr.\"},{\"name2\":\"John Doe\"}]}";

Pattern p = Pattern.compile(".*?payload\":(.*)}");
Matcher m = p.matcher(someJson);
if (m.matches()) {
  String payload = m.group(1);
}

After that payload will have the value [{"name":"John Doe Jr."},{"name2":"John Doe"}] or {"name":"John Doe"}

Some notes:

  • This regex only works as long as the payload element is the last json object within your json string.
  • As others have mentioned: It would be better (and easier) to do this with an json api (see below)
  • If you have control over the json string it might be better to return an array with just one element instead of the element directly. So you don't need to write extra code to read a single element.

With Androids JSONObject this can look like this:

JSONObject json = new JSONObject(someJson);
try {
  JSONArray payload = json.getJSONArray("payload");
} catch (Exception e) {
  // array conversion can fail for single object 
  JSONObject payload = json.getJSONObject("payload");
}
like image 144
micha Avatar answered Oct 19 '22 01:10

micha