user1781989 user1781989 - 1 month ago 5x
JSON Question

Array retrieval from JSON file

I have an array in JSON file which look like this

{ "fields": [
"name": "order_id",
"type": "INTEGER",
"position": 0
"name": "district_id",
"type": "INTEGER",
"position": 1

I'm using a TREE MODEL in retrieving the contents of the array "fields" and my code looks like this ..

public static void main(String[] args) throws JsonParseException, IOException {
File jsonFile = new File("metadata.json");
String theJsonString = jsonFile.toString();
String name = null;
String type =null;
int position = 0;
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
JsonNode rootNode = mapper.readTree(theJsonString);
JsonNode fields = rootNode.get("fields");
if (fields != null) {

for (int i = 0; i < fields.size(); i ++) {
name = fields.get("name").getTextValue();
type = fields.get("type").getTextValue();
position = fields.get("position").getIntValue();


I get the following error during the run time ::

Exception in thread "main" org.codehaus.jackson.JsonParseException: Unexpected character ('/' (code 47)): maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)
at [Source:; line: 1, column: 2]
at org.codehaus.jackson.JsonParser._constructError(
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(
at org.codehaus.jackson.impl.ReaderBasedParser._skipComment(
at org.codehaus.jackson.impl.ReaderBasedParser._skipWSOrEnd(
at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(
at metadata.JSONParser.main(

I have just started working with JSON and hence unable to find a solution. Could anybody help me resolve this?


If you want the contents of the file metadata.json then calling toString on the file will not give you that. Instead it will give you a string which holds the path to the filename.

Instead create a FileInputStream from the File like so:

FileInputStream fis = new FileInputStream(jsonFile);

The you can use it with the mapper

JsonNode rootNode = mapper.readTree(fis);

You might also want to call fields.get(i) when you are iterating through the array to access each JsonNode contained in the array.