Java正则表达式和/或字符串魔术从字符串中提取ID [英] Java regex and/or string magic to extract IDs from String

查看:311
本文介绍了Java正则表达式和/或字符串魔术从字符串中提取ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java应用程序正在运行一个第三方RESTful Web服务,该服务返回了以下JSON:

I have a Java app that is hitting a 3rd party RESTful web service that is returning the following JSON:

{"fizz":
    {"widgets":
        [
            {
                "widget_id":"295874"
            },
            {
                "widget_id":"295873"
            },
            {
                "widget_id":"295872"
            }
        ],
        "otime":1361993756
    },
    "resp":"ok"
}

通常我会使用GSON或Genson将其映射回Java POJO,但这是代码中唯一必须执行此操作的地方,我想在这里懒惰;-).

Normally I would use GSON or Genson to map this back to a Java POJO, but this is the only area of the code where I have to do this and I want to be lazy here ;-).

我正在尝试提出一种巧妙的方法,该方法可提取3个widget_id值(,`) and returns them as a List`:

I'm trying to come up with a nifty method that extracts the 3 widget_id values (, and `) and returns them as aList`:

public List<Long> extractIdsFromJson(String json) {
    // Can I solve this with a regex perhaps?
}

不确定正确的方法是什么-正则表达式,replaceAll,还有其他方法吗?预先感谢.

Not sure what the right approach is - regex, replaceAll, something else? Thanks in advance.

推荐答案

// untested
public List<Long> extractIdsFromJson(String json) {
    List<Long> list = new ArrayList<Long>();
    Matcher matcher = Pattern.compile("\"widget_id\":\"?(\\d+)\"?").matcher(json);
    while (matcher.find())
        list.add(Long.valueOf(matcher.group(1)));
    return list;
}

这篇关于Java正则表达式和/或字符串魔术从字符串中提取ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆