Saturday 8 November 2014

Jackson Streaming API to Read JSON

Hi guys
In the previous post we saw how to write JSON using Jackson. Lets see how to read JSON using Jackson Streaming API.

  1. JsonParser – Parse JSON.

JsonParser



On the other hand, use JsonParser to parse or read above file “data.json“, and display each of the values.

import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonMappingException;

public class Read {
public static void main(String[] args) {

try {

JsonFactory jfactory = new JsonFactory();

/*** read from file ***/
JsonParser jParser = jfactory.createJsonParser(new File("./src/data.json"));

// loop until token equal to "}"
while (jParser.nextToken() != JsonToken.END_OBJECT) {

String fieldname = jParser.getCurrentName();
if ("blogname".equals(fieldname)) {

// current token is "blogname",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getText()); // display oraclejavatechzone.com

}

if ("subject".equals(fieldname)) {

// current token is "subject",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getText()); // display java

}

if ("year".equals(fieldname)) {

// current token is "year",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getIntValue()); // display 2013

}

if ("posts".equals(fieldname)) {

jParser.nextToken(); // current token is "[", move next

// posts is array, loop until token equal to "]"
while (jParser.nextToken() != JsonToken.END_ARRAY) {

// display post11, post2, post3
System.out.println(jParser.getText());

}

}

}
jParser.close();

} catch (JsonGenerationException e) {

e.printStackTrace();

} catch (JsonMappingException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}
}
}

Output:
That's All guys..




No comments:

Post a Comment