0

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 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

I hope I got the answer, Thank you for your time. If I have a fixed JSON then it would have been possible right ?
@CodeDecode: I don't know that it has to be fixed. I'd expect JSON libs to provide a way to ask what type a prpoerty's value is.
1

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.

Comments

0

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

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.