简体   繁体   English

正则表达式从JSON字符串中提取对象

[英]Regex To Extract An Object From A JSON String

I have JSON String I would like to extract a Field from it Using Regex. 我有JSON字符串,我想使用Regex从中提取字段。 The field can be an Object , Array , String , int or any type. 该字段可以是ObjectArrayStringint或任何类型。 I Know the other way like looping through all the keys in the JSON and finding it. 我知道另一种方式,例如遍历JSON中的所有键并找到它。 I would like to know, This can be achieved using Regex or not. 我想知道,这可以使用Regex来实现。 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; 不合理,不,因为正则表达式不适合自行解释JSON之类的结构; as with HTML, you want a proper parser. 与HTML一样,您需要一个适当的解析器。

Instead, use any of the several Java libraries for parsing the JSON and then traversing its content; 相反,可以使用几种Java库中的任何一种来解析JSON,然后遍历其内容。 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). 在JSON网站的底部有一个列表(我看到Gson使用了很多,但是有很多选择)。

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) 无论如何,可以说我们有一个方法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),获取对象并检查,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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