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.

4
  • 3
    Don't you want to use a JSON parser instead? Commented Aug 25, 2012 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 Commented Aug 25, 2012 at 17:01
  • Can't you just use new JSONObject("your_js_string") and then work with the resulting JSONObject? Commented Aug 25, 2012 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. Commented Aug 25, 2012 at 17:19

1 Answer 1

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");
}
Sign up to request clarification or add additional context in comments.

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.