CodeDecode
CodeDecode

Reputation: 401

Regex To Extract An Object From A JSON String

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.

Upvotes: 0

Views: 4723

Answers (3)

engineercoding
engineercoding

Reputation: 832

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.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074148

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).

Upvotes: 3

Amit Agarwal
Amit Agarwal

Reputation: 396

It's better to use JSON deserialization tools (e.g. Jackson, GSON), get Object and check,

Upvotes: 0

Related Questions