I have JSON String I would like to extract a Field from it Using Regex. The field can be an Object, Array, String, int or any type. I Know the other way like looping through all the keys in the JSON and finding it. I would like to know, This can be achieved using Regex or not. Any help would be great.
3 Answers
This can be achieved using Regex or not
Not reasonably, no, because regular expressions are not well-suited to interpreting structures like JSON on their own; as with HTML, you want a proper parser.
Instead, use any of the several Java libraries for parsing the JSON and then traversing its content; there's a list of them at the bottom of the JSON site (I see Gson used a lot, but there are lots of options).
2 Comments
It can be achieved through regex, but it is simply worthless, because the you have to parse out your own variables.
Anyway, lets say we have a method getObject(String key, String JSON)
public String getObject(String key, String JSON) {
Pattern p = Pattern.compile(String.format("\"%s\":\\s*(.*),", key));
Matcher matcher = pattern.matcher(JSON);
if(matcher.find())
return matcher.group();
return null;
}
Note that this only will find the first occurence, you should modify this to your needs. However, I do recommend a parser which parses the value for you.