When parsing JSON in Java, I'm wondering if a library called jackson is often used. (Aside from the complaint that Java doesn't have a standard library that handles JSON !? Only EE8 is supported?)
I will write about how to use this jackson to parse JSON in the so-called "ketsu comma" and "end comma".
First of all, the official release of jackson at the moment (2017/6/22) is 2.8 series, and it seems that 2.8 series can not support the trailing comma. It seems that the option ALLOW_MISSING_VALUES can be used to the extent that it is regrettable, but it cannot be said that it corresponds to the so-called trailing comma.
ES5 and recent Java (which I forgot for some time) now ignore trailing commas.
js
let obj = {
key1: 1,
key2: 2,
};
let arr = [
1,
2,
];
Java
String[] ss = new String[] {
"a",
"b",
};
//・ ・ ・
enum KIND {
A,
B,
}
You can write something like this.
(Although I haven't investigated what is going on with JSON officially)
If there is a trailing comma in JSON parsing with normal jackson, a syntax error will occur, but Actually, I tried to find out if it could be handled with Option.
Looking at the issue below, it seems to correspond.
Add JsonParser.ALLOW_TRAILING_COMMA
to work for Arrays and Objects
However, it seems that official support has not been made yet, and it seems that it can be realized by using 2.9.0.pr system.
If it is maven, write as follows.
pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0.pr4</version>
</dependency>
After using 2.9.0 series, it seems that it can be supported by setting ALLOW_TRAILING_COMMA of ObjectMapper as follows.
ObjectMapper mapper = new ObjectMapper().configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true);
Object obj = mapper.readValue(json, Object.class);
I personally called it "Ketsukamma", but it doesn't come out much even if I google it. Is it a "last comma" in Japanese? However, even if I googled with "jackson trailing comma", this countermeasure did not come out easily. Finally, when I googled "jackson trailing comma", it came out.
When checking "Ketsu comma", google with "trailing comma"! That is my personal lesson this time.
Recommended Posts