简体   繁体   中英

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.

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

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.

最好使用JSON反序列化工具(例如Jackson,GSON),获取对象并检查,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM