Reputation: 18884
I am using Jackson to parse api results and this seems to be working well.
Java:
public static void jsonIn(String st){
try {
JsonFactory jfactory = new JsonFactory();
/*** read from URL ***/
JsonParser jParser = jfactory.createJsonParser(new URL(st));
// loop until token equal to "}"
while (jParser.nextToken() != JsonToken.END_ARRAY) {
String fieldname = jParser.getCurrentName();
if ("id".equals(fieldname)) {
// current token is "id",
// move to next, which is "id"'s value
try{
jParser.nextToken();
}
catch (Exception e){
}
System.out.println(jParser.getText()); // display id
}
}
jParser.close();
} catch (JsonGenerationException e) {
e.printStackTrace();
}
}
Question:
However- the results that I want (field: "id") are in the array "items". The code above starts at the first array "queries" and only sends me the 1 element named "id", which I don't care for. It then stops parsing based on the while statement and doesnt get to the "items" array. How can I change my code above to skip to the array "items" that I am interested in so that I can get the "id" fields that I want?
json:
{
"app": "Sale",
"avail": {
"type": "application/json",
},
"queries": {
"unAvailURIs": [
{
"id": "1sdf6gf3jf80dhb3",
"results": "57",
"searchTerms": "lycos.com",
"startIndex": 11
}
],
"apiSource": [
{
"title": "go****y",
"totalResults": "579000",
"auctionPhrase": "lycos.com",
"count": 10,
"startIndex": 1,
"id": "in",
}
]
},
"pullAPI": {
"search": "lycos.com"
},
"searchInformation": {
"searchTime": 0.025345,
"totalResults": "57600100",
},
"items": [
{
"id": "GD172993",
"title": "lycos.com",
....
Upvotes: 2
Views: 3171
Reputation: 18884
I seem to have missed the one SO post I was looking for: Parsing JSON Bing results with Jackson.
Thank you to @fge for explaining ObjectMapper
and readTree()
.
I simply replaced the beginning of my top try
statement as so:
try {
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createJsonParser(new URL(st));
ObjectMapper mapper = new ObjectMapper();
JsonNode input = mapper.readTree(jParser);
final JsonNode results = input.get("items");
// loop until token equal to "}"
for (final JsonNode element: results) {
JsonNode fieldname = element.get("id");
System.out.println(fieldname.toString());
Upvotes: 4