Join Alex Theedom for an in-depth discussion in this video Create a model from a JSON file, part of JSON Processing with Java EE.
- [Instructor] Okay, so go ahead and open up the ObjectExample2 class. In the loadJasonObject() method, we're going to start to write the code in the same way that we did in the previous example, but instead of creating a StringReader, we create a FileReader. So let's start as we did before. We need a JsonReader, and we need to create a factory. We do this by calling a static method on the Json class.
In this case, we're going to pass it a new FileReader, and we're going to pass it our jsonFileObject. Now, at the top of the screen, you can see that we have our jsondata-object.json file. This file is located in the resources directory. What the FileReader will do is to open this file and load in the JSON data. Just as we did before, what we need to do is to call the readObject method on the reader instance.
So we're going to create our jsonObject instance. We're going to be calling our readObject method, which reads the object, into our jsonObject. Just as before, we need to return our jsonObject. Of course, don't forget to close the reader. Now we have written the code. Let's write a unit test to verify that the JSON has been read correctly. So let's open up the ObjectExample2Test.
All we want to do here is to implement a very simple test. We could do exactly the same as what we did in the previous example, but let's do something slightly different. All I really want to do now is to write a very simple assertion to test that the value type of the object is actually Object. As before, we start with our assertion. We pass it our jsonObject, and on our jsonObject, what we have to do is call our getValueType, and the value type that we expect it to be we test in our isEqualTo method by passing it our JasonValue, calling the value type and obtaining the value type, which is Object.
We expect the value type of this jsonObject to be Object. It is a jsonObject. Now, let's execute the test. And yes, the test has passed. What this means is the value type of our object is actually Object.
In this course, discover how to use the Java Enterprise Edition (EE) JSON-Processing API. With its two programming models, JSON-Processing is one of the simplest ways to generate, query, and parse JSON data, and you'll find that implementing it in your projects is quick and easy. Join Alex Theedom as he covers an array of topics, including how to use both the object model and the streaming model, how to traverse a JSON structure, and how to parse JSON data using the extensive builder APIs. When you wrap up this course, you'll be ready to develop with this essential and powerful API.
- Working with JSON and Java
- JSON-Processing API features
- The Java EE JSON object model
- Creating a model from a JSON string
- Building a JSON model
- Traversing the JSON model
- Outputting the JSON model to a data stream
- Parsing and writing JSON data