我有一个非常复杂的字符串,如下所示,
"data":"[
{
"id": "123456",
"from":
{
"name": "ABC",
"id": "123"
},
"message": "isafh",
"story": "Best Story",
"properties":
[
{
"name": "By",
"text": "PROUD TO BE AN INDIAN",
"href": "www.xyz.com"
}
],
"privacy":
{
"value": ""
},
"type": "photo",
"created_time": "2013-10-24T07:17:28+0000",
"updated_time": "2013-10-24T07:17:28+0000"
},
{
"id": "122423456",
"from":
{
"name": "ABCaasd",
"id": "124233"
},
"message": "isafh",
"story": "Best nice Story",
"properties":
[
{
"name": "By",
"text": "PROUD TO BE AN INDIAN",
"href": "www.abc.com"
}
],
"privacy":
{
"value": ""
},
"type": "photo",
"created_time": "2013-10-24T07:17:28+0000",
},
{
Similar data as above {... }
},
]"
"next token":"1233"
这里所有JSON数据都在这些括号“[]”中,它们由“{...}”括号分隔。我想要一个来自所有花括号的消息,故事和属性。 尝试了两件事,一件是两件事,把所有东西放在一个JSON对象中,并尝试了无用的尝试来匹配正则表达式“消息:”,但即使这样也行不通。
从所有大括号中查找消息,故事和属性的方法是什么。
答案 0 :(得分:4)
正则表达式不适合解析复杂的数据结构,如JSON或HTML文档。幸运的是,我们有快速,可靠和免费的图书馆,可以很好地完成这项工作。
请参阅json.org's solution for Java或其他可以解析json.org中列出的JSON的库列表(滚动到页面底部)。
使用json.org的库解析JSON文档非常简单:
String json = "{ \"message\" : \"Hi, this is the value for the key \\\"message\\\"\" }";
JSONObject myObject = new JSONObject(json); // This line actually parses the JSON text
System.out.println(myObject.getString("message"));
答案 1 :(得分:1)
使用像google-gson https://code.google.com/p/google-gson/
这样的json库这是一个使用gson-1.7.1.jar测试的工作示例,但它也应该与最新版本一起使用。
public static void main(String[] args) {
String jsonData = "{\"data\":[{\"id\": \"123456\",\"from\": {\"name\": \"ABC\",\"id\": \"123\"},\"message\": \"isafh\",\"story\": \"Best Story\",\"properties\": [{\"name\": \"By\",\"text\": \"PROUD TO BE AN INDIAN\",\"href\": \"www.xyz.com\"}],\"privacy\": {\"value\": \"\"},\"type\": \"photo\",\"created_time\": \"2013-10-24T07:17:28+0000\",\"updated_time\": \"2013-10-24T07:17:28+0000\"},{\"id\": \"122423456\",\"from\": {\"name\": \"ABCaasd\",\"id\": \"124233\"},\"message\": \"isafh\",\"story\": \"Best nice Story\",\"properties\": [{\"name\": \"By\",\"text\": \"PROUD TO BE AN INDIAN\",\"href\": \"www.abc.com\"}],\"privacy\": {\"value\": \"\"},\"type\": \"photo\",\"created_time\": \"2013-10-24T07:17:28+0000\"}],\"next token\":\"1233\"}";
List<String> messages = parse(jsonData);
for (String message : messages) {
System.out.println(message);
}
}
public static List<String> parse(String jsonData) {
List<String> messages = new ArrayList<String>();
JsonElement jsonElement = new JsonParser().parse(jsonData);
JsonObject jsonTopObject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonTopObject.getAsJsonArray("data").getAsJsonArray();
Iterator<JsonElement> iterator = jsonArray.iterator();
while (iterator.hasNext()) {
JsonObject jsonObject = iterator.next().getAsJsonObject();
messages.add(jsonObject.get("message").getAsString());
}
return messages;
}
请注意,您提供的json数据进行了微小更改才能生效。 例如用“{”,“}”包装以形成一个json对象,并且在数据的末尾你有"created_time": "2013-10-24T07:17:28+0000",},
所以最后一个昏迷被删除了。