5

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.

user268397
  • 1,917
  • 7
  • 38
  • 56
  • 3
    Don't you want to use a [JSON parser](http://stackoverflow.com/questions/2818697/sending-and-parsing-json-in-android) instead? – assylias Aug 25 '12 at 16:53
  • I'm trying to get the payload json array from an InputStream then I'm parsing the JSONArray and the JSONObjects inside the JSONArray with a JSON Parser – user268397 Aug 25 '12 at 17:01
  • Can't you just use `new JSONObject("your_js_string")` and then work with the resulting `JSONObject`? – João Silva Aug 25 '12 at 17:07
  • All I want to do is extract the payload string and set the string to a JSONArray and work with the Json objects in the JSONArray. That's all I want to do. I don't want to use a JSON parser to get the array. – user268397 Aug 25 '12 at 17:19

1 Answers1

14

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");
}
micha
  • 47,774
  • 16
  • 73
  • 80