Running your first JSON-P 1.1 code
JSON-Pointer is the Java API for JSON processing. By processing, we mean generating, transforming, parsing, and querying JSON strings and/or objects.
In this recipe, you will learn how to use JSON Pointer to get a specific value from a JSON message in a very easy way.
Getting ready
Let's get our dependency
:
<dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> </dependency>
How to do it...
- First, we define a JSON message to represent a
User
object:
{ "user": { "email": "[email protected]", "name": "Elder", "profile": [ { "id": 1 }, { "id": 2 }, { "id": 3 } ] } }
- Now, we create a method to read it and print the values we want:
public class JPointer {
public static void main(String[] args) throws IOException{
try (InputStream is =
JPointer.class.getClassLoader().getResourceAsStream("user.json");
JsonReader jr = Json.createReader(is)) {
JsonStructure js = jr.read();
JsonPointer jp = Json.createPointer("/user/profile");
JsonValue jv = jp.getValue(js);
System.out.println("profile: " + jv);
}
}
}
The execution of this code prints the following:
profile: [{"id":1},{"id":2},{"id":3}]
How it works...
The JSON Pointer is a standard defined by the Internet Engineering Task Force (IETF) under Request for Comments (RFC) 6901. The standard basically says that a JSON Pointer is a string that identifies a specific value in a JSON document.
Without a JSON Pointer, you would need to parse the whole message and iterate through it until you find the desired value; probably lots of ifs, elses, and things like that.
So, JSON Pointer helps you to decrease the written code dramatically by doing this kind of operation in a very elegant way.
See also
- You can stay tuned with everything related to JSON-P at https://javaee.github.io/jsonp/
- The source code of this recipe is at https://github.com/eldermoraes/javaee8-cookbook/tree/master/chapter01/ch01-jsonp