Java - 日期模式匹配

时间:2013-05-14 13:06:21

标签: java android regex pattern-matching

我是Java新手。请帮我。我在下面遇到JSON响应问题:

{"GetResult":"{  \"IsDate\": [    {      \"Code\": \"200\"    },    {      \"Message\": \"Fetched successfully\"    },    {      \"ID\": \"722c8190c\",      \"Name\": \"Recruitment\",      \"Path\": \"URL\",      \"Date\": \"14 May, 2013\"    },     ]}"}

它是一个格式错误的JSON对象。所以,我使用匹配模式获取NamePathDate的数据,并成功获得NamePath,如下所示:

 Matcher matcherName = Pattern.compile("\\\\\"Name\\\\\":\\s\\\\\"[^,}\\]]+\\\\\"").matcher(Name);

Matcher matcherPath = Pattern.compile("\\\\\"Path\\\\\":\\s\\\\\"^[^,}\\]]+\\\\\"").matcher(Path);

因此,从以上几行,我可以获得PathName。所以,请帮助如何获得DateDate is 14 May, 2013的格式。请帮帮我。

2 个答案:

答案 0 :(得分:2)

这是有效的json。

点击此处jsonlint

像这样解析它

{
    "GetResult": "{  \"IsDate\": [    {      \"Code\": \"200\"    },    {      \"Message\": \"Fetched successfully\"    },    {      \"ID\": \"722c8190c\",      \"Name\": \"Recruitment\",      \"Path\": \"URL\",      \"Date\": \"14 May, 2013\"    },     ]}"
}

JSONObject parent=new JSONObject(jsonString);
JSONObject obj=parent.getJSONObject("GetResult");
JSONArray array=obj.getJSONArray("IsDate");

String jsondatestring=array.getString(2);
JSONObject datejson=new JSONObject(jsondatestring);
String date=datejson.getString("Date");

如果你想知道如何解读这些角色,试试这个

使用Commons lang libarray和StringEscapeUtils类。

只需使用

String newString=StringEscapeUtils.unescapeJava(yourString);

答案 1 :(得分:1)

匹配与您的问题几乎相同:

Matcher matcherDate = Pattern.compile("\\\\\"Date\\\\\":\\s\\\\\"([^\\\\]*)\\\\\"").matcher(brokenJson);
while (matcherDate.find()) {
    System.out.println(matcherDate.group(1));
}

然后,您可以使用SimpleDateFormat

解析日期

<强>更新即可。从文件中读取brokenJson并解析它的完整代码:

    String brokenJson = Files.toString(new File("1.dat"), Charset.defaultCharset());
    Matcher matcherDate = Pattern.compile("\\\\\"Date\\\\\":\\s\\\\\"([^\\\\]*)\\\\\"").matcher(brokenJson);
    while (matcherDate.find()) {
        System.out.println(matcherDate.group(1));
    }
相关问题