Mjson is a Java Library or API that allows you to easily convert normal Java objects into JSON objects(provided from Mjson) and then of course JSON objects back into Java objects or data types. Along with this, the library provides tools for manipulating and grabbing information from JSON objects using Java.
To avoid confusion betwen the Json object provided by the mJson API and the term JSON, whenever I say Json I am referring to the Mjson object and JSON I simply mean JSON in general.
Listen to this while reading: https://open.spotify.com/album/4g1ZRSobMefqF6nelkgibi?si=2gZxbkN4QBu67AI3-g1Mdg
Let's Begin.
There are two primary ways to get the library imported into our project. If you have Maven setup for the project, you can simply add the dependency into the pom.xml
<dependency>
<groupId>org.sharegov</groupId>
<artifactId>mjson</artifactId>
<version>1.4.0</version>
</dependency>
On the other hand, you can use the IntelliJ(cool people use this) import tool. File > Project Structure > Libraries > Plus sign
If we shall be using JSON within our Java projects, we need a way to represent the data, which is done with Json objects from the Mjson Library. Therefore, let's explore the different methods of creating such objects.
Stuff.json
{
"name": "Bob",
"age": 24,
"address": {
"streetAddress": "800 W Campbell Rd",
"city": "Richardson",
"state": "Texas",
"zipCode": 75080
},
"isCool": true
}
The JSON object above is what we want to represent within a Java String so that we can practice turning it into a Json object in Java. As you can see in the example below, representing Json as a string is quite cumbersome and annoying to do, but sometimes you will need to deal with it within your applications. Once you have it and you knows its a valid string of JSON, you can use the static read() method to take the string as a parameter and return a Json object. Example 1
//JSON object as a string
String jsonString = "{" +
"\"name\": \"Billy Bob\"," +
"\"age\": 36," +
"\"address\":" +
"{" +
"\"streetAddress\": \"800 W Campbell Rd\"," +
"\"city\": \"Richardson\"," +
"\"state\": \"TX\"," +
"\"postalCode\": \"75080\"" +
"}," +
"\"isCool\": true" +
"}";
//Convert that string into a json object
Json jsonObject = Json.read(jsonString);
//Print it out to see if it worked or not
System.out.println(jsonObject);
If you only have a string that represents part of a JSON object, that's fine too. Partials work the same. Example 2
//You can even use partials of a json object
//As long as they are in json format
String randomJson = "[45, 21, \"booty\", false]";
Json random = Json.read(randomJson);
System.out.println(random);
If you know that you need to represent an array with JSON so that you can add it to an object or something, using the array() method accepts an unlimited amount of parameters for the array and if valid returns a Json object that contains an array. If you leave the method empty, it returns an empty array--but it still works. Example 3
//Make an array using the static array() method from mJson Library
Json array = Json.array("Poopity", "doopity", false, true, 4.3245);
System.out.println(array); //Print out to see if it worked
//OR
Json emptyArray = Json.array();
System.out.println(emptyArray);
Any datatype can be represent as a JSON object or at least stored in one, and sometimes you will have a collection you want to convert into a Json object. If it's a Map collection, it will be represented in the Json object and an object because of it's key-value pair structure. Other collections like ArrayLists will be represented in the Json object as an array because its just single values with no identifier to match. Example 4
//Collections will basically be converted into arrays inside the JSON object
//Maps specifically will be turned into objects themselves rather than arrays
ArrayList<String> strings = new ArrayList<>();
strings.add("Kevin");
strings.add("Lasean");
strings.add("is");
strings.add("a");
strings.add("really");
strings.add("good");
strings.add("rapper");
HashMap<String, Boolean> nameMap = new HashMap<>();
nameMap.put("Kody", true);
nameMap.put("Noah", false);
nameMap.put("Coolmike35", false);
nameMap.put("Damascus", true);
//Turn the arraylist into a json object representing an array of strings
Json json1 = Json.make(strings);
System.out.println(json1);
//Turn the hashmap into a json object representing an object
Json json2 = Json.make(nameMap);
System.out.println(json2);
Example 5 below is a JSON file that contains an object used in the next example so that we have something to model like before. Example 5
{
"vehicleType": "car",
"name": "Tesla Model X",
"wheels": 4,
"passengers": ["Bob", "Shirley", "Ricky", "Andrew", "Trump"],
"isElectric": true
}
If you don't have a string on hand that you can translate into a Json object, using the object() method works just as fine--and defenitely more easily. It takes an unlimited amounnt of varargs that work as a key-value pair structure for the Json object. The first parameter will be the key, the one after being the value. And so on. For the values, you can plug in java data types directly and even other Json objects you have instantiated. Example 6
//Create the same JSON object as Example 5
//Use the object() method by specifying key-value pairs
Json passengers = Json.array("Bob", "Shirley", "Ricky", "Andrew", "Trump");
Json vehicle = Json.object("vehicleType", "car",
"name", "Tesla Model X",
"wheels", 4,
"passengers", passengers,
"isElectric", true);
System.out.println(vehicle);
//If you ever need a null value, use Json.nil()
Since we've now got a good amount of practice creating JSON Objects in different ways using the library, let's take a look at some of the things we can do to the objects.
Example 7
Json passengers = Json.array("Bob", "Shirley", "Ricky", "Andrew", "Trump");
Json vehicle = Json.object("vehicleType", "car",
"name", "Tesla Model X",
"wheels", 4,
"passengers", passengers,
"isElectric", true);
//Access a specific value from an json object or array
System.out.println(vehicle.at("wheels")); //Should print 4
//Store a value into a variable
boolean isElectric = (boolean) vehicle.at("isElectric").getValue(); //Should return the corresponding java type
//boolean isElectric = (boolean) vehicle.at("isElectric").getBoolean(); You can use the specific method if you know the type ahead of time
//You can also figure out what type your looking at like this
Json numWheels;
if (vehicle.at("wheels").isNumber()){ //There is a boolean returning method for pretty much any of the primary datatypes
numWheels = vehicle.at("wheels").getNumber();
}
For the above example, the at() method allows you to turn values from a JSON object or array into a Java type. The first two parameters allows you to simply navigate the index of an array or locate a value from its property name(key).
Here is another example--this messing around with an array: Example 8
Json passengers = Json.array("Bob", "Shirley", "Ricky", "Andrew", "Trump");
//Above we are turning an array into a JSON object,
//so let's practice doing the opposite
List<Object> names = passengers.asList(); //It's common to just turn an array into a List
//ALSO: This is how you access a specific elements from a Json array
System.out.println(passengers.at(2).asString()); //Print Ricky
Here are some more examples of getting information on the datatypes of a JSON object or it's values: Example 9
Json passengers = Json.array("Bob", "Shirley", "Ricky", "Andrew", "Trump");
Json vehicle = Json.object("vehicleType", "car",
"name", "Tesla Model X",
"wheels", 4,
"passengers", passengers,
"isElectric", true);
//Use methods such as the following to obtain the corresponding Java type
System.out.println(vehicle.isNull());
System.out.println(vehicle.isString());
System.out.println(vehicle.isObject());
System.out.println(vehicle.asBoolean());
System.out.println(vehicle.isNumber());
If you ever need to change the values or edit the Json objects in any way, the following examples will show you how.
The set() method is a good way. It takes as its first parameter an index(for an array) or a property name(for objects) to identify where to edit. The second parameter is the new value you want to replace the old one with. Example 10
Json passengers = Json.array("Bob", "Shirley", "Ricky", "Andrew", "Trump");
Json vehicle = Json.object("vehicleType", "car",
"name", "Tesla Model X",
"wheels", 4,
"passengers", passengers,
"isElectric", true);
System.out.println(vehicle);
vehicle.set("name", "Ford F-150"); //Change a specific value in a JSON object
System.out.println(vehicle); //Show how it changed
//Change the values in the passengers array
passengers.set(1, "Kody"); //Can also edit the arrays
System.out.println(passengers);
If you try adding a value to an array by specifiying an index that doesn't exist, you will get an IndexOutOfBoundsException. To avoid this, use the add() method for adding new values to an array. Example 11
Json passengers = Json.array("Bob", "Shirley", "Ricky", "Andrew", "Trump");
//To safely add new values to an array, use add()
System.out.println(passengers);
//passengers.set(5, "Yo momma"); Throws an exception since index 5 doesn't exist
passengers.add("Yo momma"); //Adds a new value onto the array
System.out.println(passengers);
Ever need to delete stuff from a Json object? Easy, with the delAt() method. You can also use the atDel() method which deletes a value and also returns it at the same time. Example 12
Json passengers = Json.array("Bob", "Shirley", "Ricky", "Andrew", "Trump");
Json vehicle = Json.object("vehicleType", "car",
"name", "Tesla Model X",
"wheels", 4,
"passengers", passengers,
"isElectric", true);
System.out.println(vehicle);
//Delete a value from the JSON object by its property name
vehicle.delAt("passengers");
System.out.println(vehicle);
//Delete values from an array the same way
passengers.delAt(1); //Delete Shirley
System.out.println(passengers);
These last examples showcase the with() method, which can be used to merge two JSON objects together. Example 13
Json passengers = Json.array("Bob", "Shirley", "Ricky", "Andrew", "Trump");
Json vehicle = Json.object("vehicleType", "car",
"name", "Tesla Model X",
"wheels", 4,
"passengers", passengers,
"isElectric", true);
//Merge 2 JSON objects together
Json moreVehicleInfo = Json.object("speed", 100,
"color", "purple");
System.out.println(vehicle);
vehicle.with(moreVehicleInfo); //Merge two objects
System.out.println(vehicle);
Works with arrays as well of course. Example 14
Json passengers = Json.array("Bob", "Shirley", "Ricky", "Andrew", "Trump");
Json vehicle = Json.object("vehicleType", "car",
"name", "Tesla Model X",
"wheels", 4,
"passengers", passengers,
"isElectric", true);
//Merge 2 arrays
Json morePassengers = Json.array("Post Malone", "Juice WRLD");
//Access the object and add onto the array within it
System.out.println(vehicle);
vehicle.at("passengers").with(morePassengers);
System.out.println(vehicle);
That's all I have for you in this tutorial. Now, hopefully, you have a solid understanding of how to use the mJSON Library so that you can begin utilizing JSON within your Java projects.
This video was made in accordance with this video tutorial: Mjson API: https://github.com/bolerio/mjson Here is a good book reference I used as well: https://www.amazon.com/Java-XML-JSON-Document-Processing/dp/1484243293/ref=sr_1_1?keywords=java+xml+and+json&qid=1570136505&s=gateway&sr=8-1 Discord Server: https://rebrand.ly/discordlink
{
"name": "Bob",
"age": 24,
"address": {
"streetAddress": "800 W Campbell Rd",
"city": "Richardson",
"state": "Texas",
"zipCode": 75080
},
"isCool": true
}