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.
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:
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With