Handle JSON with minimal-json

Overview

Describes how to use the Java JSON library minimal-json.

Working with JSON in Java

Until now (~ JDK 1.8) Java did not provide a JSON library as standard, so it was necessary to use some kind of library to handle JSON efficiently. Some of the most famous OSS are:

Library License Link
org.json JSON MVNRepository.com
Jackson Apache License 2.0 GitHub/MVNRepository.com
JSONIC Apache License 2.0 Official site/MVNRepository.com
Gson Apache License 2.0 GitHub/MVNRepository.com
JsonPath Apache License 2.0 GitHub/MVNRepository.com

You can find out how to use each library by searching Qiita or the Internet, so I will not cover it in this article.

minimal-json? As the name implies, it's a small Java library focused on reading and writing JSON. It is published under the MIT License. Looking at the README.md of the repository, will come out such that want to say, "This really was that?" Graph showing the high performance.

The number of classes is not very large, and it seems that there are only 15 below in version 0.9.4. The file size of the jar is 29.7 KB.

https://github.com/ralfstx/minimal-json/tree/master/com.eclipsesource.json/src/main/java/com/eclipsesource/json

  1. Json.java
  2. JsonArray.java
  3. JsonHandler.java
  4. JsonLiteral.java
  5. JsonNumber.java
  6. JsonObject.java
  7. JsonParser.java
  8. JsonString.java
  9. JsonValue.java
  10. JsonWriter.java
  11. Location.java
  12. ParseException.java
  13. PrettyPrint.java
  14. WriterConfig.java
  15. WritingBuffer.java

Developmental status

According to GitHub Release, the last release was 2015/07/20, latest commit is 2016 six months ago. / 10/25. It seems that the development itself is still going on.

Why minimal-json?

If you just want to read and write simple JSON, Gson and Jackson have too many functions, and org.json, which has only simple functions, has a JSON license [^ json], so there was no choice unexpectedly. .. This minimal-json can only be used to parse JSON, but as mentioned above it consists of only 15 classes and the MIT License / LICENSE), so it can be an alternative if you want to use org.json.

Note that this library does not have the ability to map to objects as provided by Gson and Jackson, so if you need such a feature, you should use a different library than implementing the mapping code yourself. It's better to use it.


Introduction

Just add one line to your build.gradle dependencies. At the time of writing the article, the latest version was 0.9.4.

Gradle

build.gradle


dependencies {
    compile 'com.eclipsesource.minimal-json:minimal-json:0.9.4'

Maven

pom.xml


<dependency>
    <groupId>com.eclipsesource.minimal-json</groupId>
    <artifactId>minimal-json</artifactId>
    <version>0.9.4</version>
</dependency>

Other than the above, please see here.


use

Generate JSON string

You can create an empty object with new and add the key and value to it with the add method. It can be a JSON string with the toString () method.

final JsonObject json = new JsonObject();
json.add("name", "Bill");
json.add("age", 24);
System.out.println(json.toString());

output


{"name":"Bill","age":24}

Creating a JsonObject object from a string

Pass the JSON string to Json # parse and retrieve the JSON Object with asObject ().

final JsonObject json = Json.parse(jsonStr).asObject();

Extracting the value

For String / int / double / float / long / boolean, there is a dedicated get ~~ method. If the JSON you load is completely under the control of the application developer and the format is fixed, you may use these methods.

Specify the key as a string and retrieve the value. In the second argument, specify the default value when there is no key.

json.getString("name", "")

For example, suppose you have a simple JSON like this:

{"name": "John", "age": 28}

The code that parses this, retrieves the value, and displays it on standard output is as follows.

java


final JsonObject json = Json.parse("{\"name\": \"John\", \"age\": 28}").asObject();
System.out.println(json.getString("name", "-"));
System.out.println(json.getInt("age", -1));

Note that age is an int, so if you try to retrieve it as a String, you will get `` `java.lang.UnsupportedOperationException```.

Code with exception


System.out.println(json.getString("age", "-"));

Exceptions and messages


java.lang.UnsupportedOperationException: Not a string: 28

If you want to retrieve the value of int as a String, you can use toString () on the JsonValue object retrieved by get (key).

System.out.println(json.get("age").toString());

However, note that json.get ("age") can return null in that case.

final JsonValue nullable = json.get("age");
if (nullable != null) {
    System.out.println(nullable.toString());
}

If you can use Optional, you should use it together.

Optional.ofNullable(json.get("age"))
        .map(JsonValue::toString)
        .ifPresent(System.out::println);

Nullable

For example, suppose you have a simple JSON like this:

{"name": "John", "age": 28, "nullable": null}

When I try to getString for "nullable", I get the following error: I would like the defaultValue to be useful ...

java.lang.UnsupportedOperationException: Not a string: null
	at com.eclipsesource.json.JsonValue.asString(JsonValue.java:389)
	at com.eclipsesource.json.JsonObject.getString(JsonObject.java:674)
	at jp.toastkid.libs.epub.EpubMetaData.readJson(EpubMetaData.java:114)

By the way, the exception can be avoided with the following, but it is displayed as null in the standard output.

Optional.ofNullable(json.get("nullable"))
        .map(JsonValue::toString)
        .ifPresent(System.out::println);

I thought "Optional was such a specification" and executed the following code to solve it. This null is not a Java null but a JSON literal null (com.eclipsesource.json.JsonLiteral It seems that it was interpreted as /main/java/com/eclipsesource/json/JsonLiteral.java)).

Survey code


Optional.ofNullable(json.get("nullable"))
        .map(Object::getClass)
        .map(Class::getName)
        .ifPresent(System.out::println);

output


com.eclipsesource.json.JsonLiteral

Well, I think you've noticed it soon after looking at it so far. When dealing with values retrieved from JSON in this library, it is safer to retrieve them with get and access them via the JsonValue object, and null checking is easier. It works better when combined with Optional.


Unfortunately

JsonArray is not compatible with Java 8

JsonArray class implements Iterable is. Since there is no stream (), the Stream API cannot be used, and only forEach is provided as a method that can be used for iteration. I want at least filter / map.

There is no has method

The reason I brought out Optional is that there is no method to check the existence of the key. Well, with that in mind, I think it's a bit tough to use this library below 1.7 ... It's a code with a lot of null checks in if.


Summary

I described the features and introduction method of the Java library minimal-json that can operate JSON very easily. It is safer to use get (key) to retrieve the value, and it feels better to use it in combination with Optional.

[^ json]: The JSON licensed library is allowed to be used by companies that have adopted a conservative software license management policy with the interpretation of The Software shall be used for Good, not Evil. There are cases where it cannot be done. There seems to be a view that "JSON license is not applied to the code of org.json", but it can be judged that there is no need to take unnecessary risk as long as there is an alternative in Java's JSON library. I think it's highly sexual. By the way, the Android SDK includes org.json library, but there is a problem especially in terms of licensing. I haven't heard that there is.

Recommended Posts

Handle JSON with minimal-json
Handle JSON effortlessly with Alamofire's respone Json
Diffed with JSON
Import JSON with SolrJ
Handle files with NIO.2.
JSON validation with JSON schema
Handle devise with Rails
Format JSON with org.json
Handle JSON in cross domain with Play Framework
[Java] JSON communication with jackson
Handle dates with Javascript (moment.js)
[Ruby] Handle instance variables with instance methods
Handle DatePicker with Ruby / gtk3 + glade3
[Java] Get Json from URL and handle it with standard API (javax.script)
Handle application/pdf response as File with ruby
Apply regular expression matching with JSON Sassert
Create a GUI JSON Viewer with Ruby/GTK3
[Java] Handle Excel files with Apache POI
How to handle sign-in errors with devise
Working with huge JSON in Java Lambda
Convert JSON to TSV and TSV to JSON with Ruby