To Useful Java links project / To Hello World project
The Json parsers libraries offer 3 main methods for processing JSON and 1 additional:
- Data Binding converts JSON to and from POJOs based either on property accessor conventions or annotations.
- Tree Model provides a mutable in-memory tree representation of a JSON document.
- Streaming API (aka "Incremental parsing/generation") reads and writes JSON content as discrete events.
- (additional) XPath analog - working with a JSON structure in the same way as XPath expression are used in combination with an XML document.
Property | Fastjson | Gson | LoganSquare | JSON java | Moshi | Ig json parser | Jackson | Genson | JsonPath | JSON.simple |
---|
- Data bind | Yes| Yes | Yes | - | Yes | Yes | Yes | Yes | - | -
- Tree Model | - | Yes| - | Yes | - | - | Yes | - | - | Yes
- Streaming API | - | Yes| - | - | - | - | Yes | - | -
- Analog XPath | Yes | - | - | - | - | - | Yes | - | Yes| -
- Generation classes at compile-time | - | - | Yes | - | - | Yes | - | - | -| -
- Github's star | 4851 | 4120 | 2188 | 1937 | 1732 | 921 | 881 | 108 | 849 | 161
- Working with static inner class | Yes | Yes | No | - | Yes | No | Yes | Yes | - | -
- Required annotations | No | No | Yes | - | No | Yes | No | No | - | -
From useful-java-links:
- Alibaba Fastjson Fast JSON Processor , github's star - 4851. User guide and Hello World examples. License: Apache 2.
- Gson - Serializes objects to JSON and vice versa. Good performance with on-the-fly usage, github's star - 4120. User guide and Hello World examples. License: Apache 2.
- LoganSquare - JSON parsing and serializing library based on Jackson's streaming API. Outpeforms GSON & Jackson's library, github's star - 2188. User guide and Hello World examples. License: Apache 2.
- JSON java A reference implementation of a JSON package in Java, github's star - 1937. User guide and Hello World examples. License: Crockford's license (MIT License + "Good, not Evil").
- Square Moshi A modern JSON library for Android and Java , github's star - 1732. User guide and Hello World examples. License: Apache 2
- Instagram Ig json parser Fast JSON parser for java projects, github's star - 921. User guide and Hello World examples. License: BSD 3.
- Jackson - Similar to GSON but has performance gains if you need to instantiate the library more often. Subprojects: Jackson core Core part of Jackson, Jackson databind Core part of Jackson that defines Streaming API as well as basic shared abstractions, github's star - 881. User guide and Hello World examples. License: Apache 2.
- JSON.simple - A simple Java toolkit for JSON. You can use json-simple to encode or decode JSON text, github's star - 161. User guide and Hello World examples. License: Apache 2.
- Genson -Powerful and easy to use Java to JSON conversion library, github's star - 108. User guide and Hello World examples. License: Apache 2.
- Jayway JsonPath Java JsonPath implementation, github's star - 849. User guide and Hello World examples. License: Apache 2.
- Alibaba Fastjson Fast JSON Processor , github's star - 4851. User guide and Hello World examples. License: Apache 2.
- Jsonschema2pojo Generates Java types from JSON Schema (or example JSON) and annotates those types for data-binding with Jackson 1.x or 2.x, Gson, etc. , github's star - 1664. User guide and Hello World examples. License: Apache 2.
- Json schema validator A JSON Schema validation implementation in pure Java, which aims for correctness and performance, in that order, also can generate Java types from JSON Schema or versa versa, github's star - 547. User guide and Hello World examples. License: GNU Lesser 3/Apache 2.
Methods | Fastjson | Gson | LoganSquare | Moshi | Ig json parser | Jackson | Genson |
---|---|---|---|---|---|---|---|
Initialization | --- | Gson gson = new Gson() |
--- | Moshi moshi = new Moshi. Builder().build(); JsonAdapter<Human> jsonAdapter = moshi.adapter(Human.class) |
--- | ObjectMapper mapper = new ObjectMapper() |
Genson genson = new Genson() |
Building json | JSON.toJSONString(human) |
gson.toJson(human) |
LoganSquare.serialize(human) |
jsonAdapter.toJson(human) |
Human__JsonHelper.serializeToJson(human) |
mapper.writeValueAsString(human) |
genson.serialize(human) |
Parsing json | JSON.parseObject(jsonString, Human.class) |
gson.fromJson(jsonString, Human.class) |
LoganSquare.parse(jsonString, Human.class) |
jsonAdapter.fromJson(jsonString) |
Human__JsonHelper.parseFromJson(jsonString) |
mapper.readValue(jsonString, Human.class) |
genson.deserialize(jsonString, Human.class) |
Arguments for every example (Json and Java classes):
json:
jsonString =
{
"message": "Hi",
"place": {
"name": "World"
}
}
Java classes
class Human {
private String message;
private Place place;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
public void say() {
System.out.println();
System.out.println(getMessage() + " , " + getPlace().getName() + "!");
}
}
class Place {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// init class
Place place = new Place();
place.setName("World");
Human human = new Human();
human.setMessage("Hi");
human.setPlace(place);
Examples:
1) Fastjson:
// convert to json
String jsonString = JSON.toJSONString(human);
System.out.println("json " + jsonString); // print "json {"message":"Hi","place":{"name":"World"}}"
// convert from json
Human newHuman = JSON.parseObject(jsonString, Human.class);
newHuman.say(); // print "Hi , World!"
2) Gson
// convert to json
Gson gson = new Gson();
String jsonString = gson.toJson(human);
System.out.println("json " + jsonString); // print "json {"message":"Hi","place":{"name":"World"}}"
// convert from json
Human newHuman = gson.fromJson(jsonString, Human.class);
newHuman.say(); // print "Hi , World!"
3) LoganSquare
@JsonObject
public class Human {
@JsonField(name="message")
public String message;
@JsonField(name="place")
public Place place;
....
// convert to json
String jsonString = LoganSquare.serialize(human);
System.out.println("json " + jsonString); // print "json {"place":{"name":"World"},"message":"Hi"}"
// convert from json
Human newHuman = LoganSquare.parse(jsonString, Human.class);
newHuman.say(); // print "Hi , World!"
4) Moshi
// convert to json
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<Human> jsonAdapter = moshi.adapter(Human.class);
String jsonString = jsonAdapter.toJson(human);
System.out.println("json " + jsonString); // print "json {"message":"Hi","place":{"name":"World"}}"
// convert from json
Human newHuman = jsonAdapter.fromJson(jsonString);
newHuman.say(); // print "Hi , World!"
5) Ig json parser
@JsonType
public class Human {
@JsonField(fieldName="message")
public String message;
@JsonField(fieldName="place")
public Place place;
...
// convert to json
String jsonString = Human__JsonHelper.serializeToJson(human);
System.out.println("json " + jsonString); // print "json {"place":{"name":"World"},"message":"Hi"}"
// convert from json
Human newHuman = Human__JsonHelper.parseFromJson(jsonString);
newHuman.say(); // print "Hi , World!"
5. Jackson
// convert to json
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(human);
System.out.println("json " + jsonString); // print "json {"message":"Hi","place":{"name":"World"}}"
// convert from json
Human newHuman = mapper.readValue(jsonString, Human.class);
newHuman.say(); // print "Hi , World!"
6. Genson
// convert to json
String jsonString = new Genson().serialize(human);
System.out.println("json " + jsonString); // print "json {"message":"Hi","place":{"name":"World"}}"
// convert from json
Human newHuman = new Genson().deserialize(jsonString, Human.class);
newHuman.say(); // print "Hi , World!"
Parsing json:
Methods | Gson | Jackson | JSON java | JSON.simple |
---|---|---|---|---|
Initialization | JsonParser parser = new JsonParser() |
new ObjectMapper() |
- | - |
Json parsing | parser.parse(<string>) |
mapper.readValue(<string>, JsonNode.class) |
new JSONObject(<string>) |
(JSONObject) JSONValue.parse(<string>) |
Get main object | root.getAsJsonObject() |
- | - | - |
Get string value | root.get(<name>).getAsString() |
root.get(<name>).asText() |
root.getString(<name>) |
(String) root.get(<name>) |
Get child object | root.getAsJsonObject(<name>) |
root.get(<name>) |
root.getJSONObject(<name>) |
(JSONObject) root.get(<name>) |
Building json:
Methods | Gson | Jackson | JSON java | JSON.simple |
---|---|---|---|---|
Initialization | - | new ObjectMapper() |
- | - |
Create main object | new JsonObject() |
mapper.createObjectNode() |
new JSONObject() |
new JSONObject() |
Add string field | root.addProperty(<name>, <string>) |
root.put(<name>, <string>) |
root.put(<name>, <string>) |
root.put(<name>, <string>) |
Add child object | root.add(<name>, <object>); |
root.putObject(<name>) |
root.put(<name>, <object>) |
root.put(<name>, <object>) |
Examples:
- Parsing json using gson
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse("{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}");
JsonObject rootObject = jsonElement.getAsJsonObject(); // get main object
String message = rootObject.get("message").getAsString(); // get field "message" as string
JsonObject childObject = rootObject.getAsJsonObject("place"); // get Place object
String place = childObject.get("name").getAsString(); // get field "name"
System.out.println(message + " " + place); // pring "Hi World!"*/
- Building json using Gson
JsonObject rootObject = new JsonObject(); // create main object
rootObject.addProperty("message", "Hi");
JsonObject childObject = new JsonObject(); // create "Place" object
childObject.addProperty("name", "World!");
rootObject.add("place", childObject); // save child object to "place" field
Gson gson = new Gson();
String json = gson.toJson(rootObject);
System.out.println(json); // print "{"message":"Hi","place":{"name":"World!"}}"
- Parsing json using Jackson
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue("{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}", JsonNode.class);
String message = rootNode.get("message").asText();
JsonNode childNode = rootNode.get("place"); // get "Place" object
String place = childNode.get("name").asText();
System.out.println(message + " " + place); // print "Hi World!"
- Building json using Jackson
OutputStream outputStream = new ByteArrayOutputStream();
ObjectMapper mapper = new ObjectMapper();
ObjectNode rootNode = mapper.createObjectNode(); // create main object
rootNode.put("message", "Hi");
ObjectNode childNode = rootNode.putObject("place"); // create child object
childNode.put("name", "World!");
mapper.writeValue(outputStream, childNode);
System.out.println(outputStream.toString()); // print "{"message":"Hi","place":{"name":"World!"}}"
- Parsing and building json using Json Java
// convert Java to json
JSONObject root = new JSONObject(); // create main object
root.put("message", "Hi");
JSONObject place = new JSONObject(); // create "Place" object
place.put("name", "World!");
root.put("place", place);
String json = root.toString();
System.out.println(json); // print "{"message":"Hi","place":{"name":"World!"}}"
System.out.println();
// convert json to Java
JSONObject jsonObject = new JSONObject(json);
String message = jsonObject.getString("message");
String name = jsonObject.getJSONObject("place").getString("name");
System.out.println(message + " " + name); // print "Hi World!"
- Parsing json using JSON.simple
JSONObject obj = (JSONObject) JSONValue.parse(json);
String message = (String) obj.get("message");
place = (JSONObject) obj.get("place");
String name = (String) place.get("name");
System.out.println(message + " " + name);
- Building json using JSON.simple
JSONObject root = new JSONObject();
root.put("message", "Hi");
JSONObject place = new JSONObject();
place.put("name", "World!");
root.put("place", place);
String json = root.toJSONString();
System.out.println(json);
Parsing json:
Methods | Gson | Jackson |
---|---|---|
Initialization | - | new JsonFactory() |
Parsing json | reader = new JsonReader((<input_stream>) |
parser = jsonFactory.createParser(<string>) |
Has next token | reader.hasNext() |
parser.hasCurrentToken() |
Get token type | reader.peek() |
parser.nextToken() |
Get next token | reader.nextString() reader.beginObject() reader.endObject() and so on |
parser.nextToken() |
Skip token | reader.skipValue() |
parser.nextToken() |
Get string | reader.nextString() |
parser.getText() |
Building json:
Methods | Gson | Jackson |
---|---|---|
Initialization | writer = new JsonWriter(<output_stream>) | generator = new JsonFactory().createGenerator(<output_stream>, <code_page>) |
Start object token | writer.beginObject() |
generator.writeStartObject() |
End object token | writer.endObject() |
generator.writeEndObject() |
Name field token | writer.name(<name>) |
generator.writeFieldName(<name>) |
String value token | writer.value(<string>) |
generator.writeStringField(<name>, <string>) |
Examples:
- Parsing json using Gson
String str = "{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}";
InputStream in = new ByteArrayInputStream(str.getBytes(Charset.forName("UTF-8")));
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
while (reader.hasNext()) {
JsonToken jsonToken = reader.peek();
if(jsonToken == JsonToken.BEGIN_OBJECT) {
reader.beginObject();
} else if(jsonToken == JsonToken.END_OBJECT) {
reader.endObject();
} if(jsonToken == JsonToken.STRING) {
System.out.print(reader.nextString() + " "); // print Hi World!
} else {
reader.skipValue();
}
}
reader.close();
- Building json using Gson
OutputStream outputStream = new ByteArrayOutputStream();
JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.beginObject();
writer.name("message");
writer.value("Hi");
writer.name("place");
writer.beginObject();
writer.name("name");
writer.value("World!");
writer.endObject();
writer.endObject();
writer.close();
System.out.println(outputStream.toString()); // print "{"message":"Hi","place":{"name":"World!"}}"
- Parsing json using Jackson
JsonFactory jsonFactory = new JsonFactory();
JsonParser jsonParser = jsonFactory.createParser("{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}");
JsonToken jsonToken = jsonParser.nextToken();
while(jsonParser.hasCurrentToken()) {
if(jsonToken == VALUE_STRING) {
System.out.print(jsonParser.getText() + " "); // print "Hi World!"
}
jsonToken = jsonParser.nextToken();
}
- Building json using Jackson
JsonFactory jsonFactory = new JsonFactory();
OutputStream outputStream = new ByteArrayOutputStream();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(outputStream, JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("message", "Hi");
jsonGenerator.writeFieldName("place");
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "World!");
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
jsonGenerator.close();
System.out.println(outputStream.toString()); // print "{"message":"Hi","place":{"name":"World!"}}"
Methods: | JsonPath | FastJson | Jackson |
---|---|---|---|
Type | XPath-like | XPath-like | JSON Pointer-like |
Initialization | - | - | mapper = new ObjectMapper() |
Get value using template | JsonPath.read(<json>, <template>) |
JSONPath.eval(<java_object>, <template>) |
mapper.readTree(<json>).at(<template>) |
Get collection using template | JsonPath.read(<json>, <template>) |
JSONPath.eval(<java_object>, <template>) |
mapper.readTree(<json>).at(<template>) |
- Using JsonPath
String jsonHiWorld = "{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}\"";
String message = JsonPath.read(jsonHiWorld, "$.message");
String place = JsonPath.read(jsonHiWorld, "$.place.name");
System.out.println(message + " " + place); // print "Hi World!"
- Using FastJson
String jsonString = "{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}\"";
Human newHuman = JSON.parseObject(jsonString, Human.class);
Object message = JSONPath.eval(newHuman, "$.message");
Object world = JSONPath.eval(newHuman, "$.place.name");
System.out.println(message + " " + world); // print Hi World
- More complex example using JsonPath
List<String> authors = JsonPath.read(json, "$.store.book[*].author");
System.out.println("authors: " + authors); // print ["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]
List<Map<String, Object>> expensiveBooks = JsonPath
.using(Configuration.defaultConfiguration())
.parse(json)
.read("$.store.book[?(@.price > 22)].title", List.class);
System.out.println(expensiveBooks); // print ["Hello, Middle-earth! "]
String json = "{\n" +
" \"store\": {\n" +
" \"book\": [\n" +
" {\n" +
" \"category\": \"reference\",\n" +
" \"author\": \"Nigel Rees\",\n" +
" \"title\": \"Sayings of the Century\",\n" +
" \"price\": 8.95\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"Evelyn Waugh\",\n" +
" \"title\": \"Sword of Honour\",\n" +
" \"price\": 12.99\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"Herman Melville\",\n" +
" \"title\": \"Moby Dick\",\n" +
" \"isbn\": \"0-553-21311-3\",\n" +
" \"price\": 8.99\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"J. R. R. Tolkien\",\n" +
" \"title\": \"Hello, Middle-earth! \",\n" +
" \"isbn\": \"0-395-19395-8\",\n" +
" \"price\": 22.99\n" +
" }\n" +
" ],\n" +
" \"bicycle\": {\n" +
" \"color\": \"red\",\n" +
" \"price\": 19.95\n" +
" }\n" +
" },\n" +
" \"expensive\": 10\n" +
"}";
- Using Jackson
ObjectMapper mapper = new ObjectMapper();
String jsonHiWorld = "{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}\"";
String message = mapper.readTree(jsonHiWorld).at("/message").asText();
String place = mapper.readTree(jsonHiWorld).at("/place/name").asText();
System.out.println(message + " " + place); // print "Hi World!"
- Using Jackson ( More complex example)
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
String author = root.at("/store/book/3/title").asText();
System.out.println(author); // print ["Hello, Middle-earth! "]
...
private final static String json = "{\n" +
" \"store\": {\n" +
" \"book\": [\n" +
" {\n" +
" \"category\": \"reference\",\n" +
" \"author\": \"Nigel Rees\",\n" +
" \"title\": \"Sayings of the Century\",\n" +
" \"price\": 8.95\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"Evelyn Waugh\",\n" +
" \"title\": \"Sword of Honour\",\n" +
" \"price\": 12.99\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"Herman Melville\",\n" +
" \"title\": \"Moby Dick\",\n" +
" \"isbn\": \"0-553-21311-3\",\n" +
" \"price\": 8.99\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"J. R. R. Tolkien\",\n" +
" \"title\": \"Hello, Middle-earth! \",\n" +
" \"isbn\": \"0-395-19395-8\",\n" +
" \"price\": 22.99\n" +
" }\n" +
" ],\n" +
" \"bicycle\": {\n" +
" \"color\": \"red\",\n" +
" \"price\": 19.95\n" +
" }\n" +
" },\n" +
" \"expensive\": 10\n" +
"}";
Online resources:
- jsonschema2pojo.org - generate Java classes from json or json schema with annotations Jackson 1, Jackson2 and Gson,
- json-schema-validator.herokuapp.com - validation json using json schema, generate json/Java classes from json schema and so on,
Examples:
- Generation Java classes using jsonschema2pojo from Java code
// Init json
String source = "{\n" +
" \"type\":\"object\",\n" +
" \"properties\": {\n" +
" \"messageHiWorld\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"bar\": {\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" \"baz\": {\n" +
" \"type\": \"boolean\"\n" +
" }\n" +
" }\n" +
"}";
// Init config
JCodeModel codeModel = new JCodeModel();
GenerationConfig config = new DefaultGenerationConfig() {
@Override
public boolean isGenerateBuilders() { // set config option by overriding method
return true;
}
};
// Generate Java POJO from json
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(), new SchemaStore()), new SchemaGenerator());
mapper.generate(codeModel, "HelloWorldClass", "com.github.vedenin", source);
// Save generated class to file
File directory = new File("helloworlds/3.8-json/jsonschema2pojo/output");
directory.mkdirs();
codeModel.build(directory);
// Show generated class
File cls = new File("helloworlds/3.8-json/jsonschema2pojo/output/com/github/vedenin/HelloWorldClass.java");
String codeHelloWorld = Files.toString(cls, Charsets.UTF_8);
System.out.println(codeHelloWorld);
- Validate Json using json schema (using jsonschema2pojo)
final JsonNode fstabSchema = Utils.loadResource("/fstab.json");
final JsonNode good = Utils.loadResource("/fstab-good.json");
final JsonNode bad = Utils.loadResource("/fstab-bad.json");
final JsonNode bad2 = Utils.loadResource("/fstab-bad2.json");
final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
final JsonSchema schema = factory.getJsonSchema(fstabSchema);
ProcessingReport report;
report = schema.validate(good);
System.out.println(report);
report = schema.validate(bad);
System.out.println(report);
report = schema.validate(bad2);
System.out.println(report);
- Generation Java classes using jsonschema2pojo and maven plugin
- Using this maven pom.xml, change sourceDirectory and targetPackage
<build>
<plugins>
<plugin>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>0.4.22</version>
<configuration>
<sourceDirectory>${basedir}/src/main/resources</sourceDirectory>
<targetPackage>com.github.vedenin</targetPackage>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
- Save json shema to sourceDirectory
- After maven/install Java classes will be generated
Documentations for every library:
All examples:
- Alibaba Fastjson
- Gson
- LoganSquare
- JSON java
- Square Moshi
- Instagram Ig json parser
- Jackson
- Genson
- Jayway JsonPath
- Jsonschema2pojo
- Json schema validator
If you want to help this project, see this guidelines