Java Reference
In-Depth Information
} else if (event.equals(Event.VALUE_NUMBER)) {
jsonVal = jsonParser.getInt();
}
jsonMap.put(jsonKeyNm, jsonVal);
}
person.setFirstName((String) jsonMap.get("firstName"));
person.setMiddleName((String) jsonMap.get("middleName"));
person.setLastName((String) jsonMap.get("lastName"));
person.setGender((String) jsonMap.get("gender"));
person.setAge((Integer) jsonMap.get("age"));
return "display_populated_obj";
}
}
In order to read and parse JSON data using the JSON-P streaming API, we need
to obtain an implementation of the JsonParser interface. The Json class has
two overloaded versions of a createParser() method we can use to obtain a
JsonParser implementation. One version of Json.createParser() takes an
instance of java.io.InputStream (or one of its subclasses) as its sole parameter,
and the other version takes an instance of java.io.Reader (or one of its subclasses)
as its sole parameter. In our example, we use the second version, passing an instance
of java.io.StringReader (which extends java.io.Reader ) that contains our JSON
string as a parameter.
Once we obtain a reference to JsonParser , we invoke its hasNext() method in a
while loop. The JsonParser.hasNext() method returns true if there are more
property names or values to read from the JSON string, otherwise it returns false .
Inside the while loop, we invoke JsonParser.next() . This method returns an
instance of the JsonParser.Event enum. The specific value of the JsonParser.
Event enum we get from JsonParser.next() lets us know what type of data we
are reading (key name, string value, numeric value, and so on). In our example, our
JSON string contains only string and numeric values, so we only check for those two
value types by comparing the JsonParser.Event instance we got from JsonParser.
next() against Event.VALUE_STRING and Event.VALUE_NUMBER , respectively. We
also check for a JSON key name by comparing the obtained value against Event.KEY_
NAME . Once we have read a key/value pair combination from our JSON string, what
we do with it depends on our application requirements. In our example, we simply
populate a hash map using the corresponding values from our JSON string.
 
Search WWH ::




Custom Search