我无法从内部元素访问嵌套对象的数据。这是json字符串 -
{"created_at":"Tue Jun 14 04:06:55 +0000 2016",
"id":7426,
"id_str":"7425",
"text":"sample",
"user":{"id":529094887,"id_str":"529094887","name":"One Direction Japan","screen_name":"1D_OfficialJP"}
"entities":{"hashtags":[{"text":"ChoiceLoveSong"},{"text":"1DJP"],"media_url":"http:\/\/pbs.twimg.com\/media\/Ck4ijC2UkAA59rU.jpg",]}}
这是我的代码 -
try{ JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(jsontext);
createdat = (String) jsonObject.get("created_at");
System.out.println(createdat);
twittertext = (String) jsonObject.get("text");
System.out.println(twittertext);
if (jsonObject.get("id")!= null)
id = (long) jsonObject.get("id");
System.out.println(id);
id_str = (String) jsonObject.get("id_str");
System.out.println(id_str);
// loop array
JsonNode json = new ObjectMapper().readTree(jsontext);
JsonNode user_fields = json.get("user");
name = user_fields.get("name").asText();
System.out.println(name);
scrname=user_fields.get("screen_name").asText();
System.out.println(scrname);
JsonNode entities_fields = json.get("entities");
String hashtags = entities_fields.get("hashtags").asText();
System.out.println("hashtags is "+ hashtags);
JSONArray hashtagsContent = (JSONArray) jsonObject.get("hashtags");
Iterator<String> entitiesNames = entities_fields.getFieldNames();
while (entitiesNames.hasNext()) {
System.out.println(entitiesNames.next());
}
jsonObject.get("user_mentions");
}
// followed by catch block ....
实际上我对从hashtag数组中提取数据感兴趣,特别是我想将这些数据存储在一个数组中。上面的代码我只能打印键而不是实体对象的值。此外,阵列中的元素数量可能会有所不同