At around 5:10 p.m. yesterday, I solved the last bug, breathed a sigh of relief, and prepared to shut down for work. But then the boss walked up to me with a mysterious smile on his face, and I knew he was up to no good. Sure enough, he threw me a new requirement to parse JSON in Java and come up with the best solution in half an hour.
But the hope of leaving work early was dashed. Still, there is hope of leaving work on time. So I rolled up my sleeves and started researching, and to my surprise, it took me less than 10 minutes to figure out the best solution. But I pretended I hadn’t figured it out yet, and in the time before I left work I put it together into this article that you see here.
What is JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write, and even easier to parse and generate for machines. JSON is a text format that is completely independent of the programming language, but its format is very consistent with the conventions of the C language family (C, C++, C#, Java, JavaScript, Python, etc.). This quality makes JSON an ideal format for data exchange.
JSON is built on two common data structures:
- Key/value pairs.
- The array.
This makes it possible to exchange JSON between programming languages that are also based on these structures. There are many third-party libraries for parsing JSON in Java, such as the following.
A lot, right? But in daily development, only four are most commonly used: Gson, Jackson, org.json and Alibaba’s Fastjson. Now let’s do a simple comparison.
02, Gson
Gson is an open source library provided by Google that serializes Java objects into JSON strings, as well as deserializing (parsing) JSON strings into matching Java objects.
Before using Gson, you need to introduce Gson’s dependencies into your project.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
<scope>compile</scope>
</dependency>
Copy the code
1) Simple examples
Gson gson = new Gson();
gson.toJson(18); / / = = > 18
gson.toJson("Silent King II."); // ==> "Silent King 2"
Copy the code
The above code creates a Gson object with the new keyword and then calls its toJson() method to convert the integer and string into A JSON string.
Similarly, you can call the fromJson() method to parse simple JSON strings into integers and strings.
int one = gson.fromJson("18".int.class);
Integer one1 = gson.fromJson("18", Integer.class);
String str = gson.fromJson("\" King of Silence ii \", String.class);
Copy the code
2) Complex examples
The Cmower class has two fields: the integer AGE and the string name.
class Cmower {
private int age = 18;
private String name = "Silent King II.";
}
Copy the code
Convert it to a JSON string.
Gson gson = new Gson();
String json = gson.toJson(new Cmower());
System.out.println(json);
Copy the code
The output is:
{"age":18."name":"Silent King II."}
Copy the code
String JSON can then be parsed into Java objects using the fromJson() method.
gson.fromJson(json, Cmower.class);
Copy the code
3) Array examples
Gson gson = new Gson();
int[] ints = {1.2.3.4.5};
String[] strings = {"Heavy"."Silent"."Two"};
// Convert to JSON string
gson.toJson(ints); / / = = > [1, 2, 3, 4, 5]
gson.toJson(strings); // ==> [" shen ", "mo "," Wang 2 "]
// Parse to an array
int[] ints2 = gson.fromJson("[1, 2, 3, 4, 5]".int[].class);
String[] strings2 = gson.fromJson([\" sink \", \" silence \", \" King 2 \"]", String[].class);
Copy the code
The array handling is still very simple, and the toJson() and fromJson() methods are still called.
4) Collection examples
Gson gson = new Gson();
List<String> list = new ArrayList<>(Arrays.asList("Heavy"."Silent"."Two"));
String json = gson.toJson(list); // ==> [" shen "," mo "," Wang 2 "]
Copy the code
There’s nothing special about turning collections into JSON strings, but parsing JSON strings into collections is a bit different than the previous approach.
Type collectionType = new TypeToken<ArrayList<String>>(){}.getType();
List<String> list2 = gson.fromJson(json, collectionType);
Copy the code
We need to use the com. Google. Gson. Reflect the TypeToken and Java. Lang. Reflect. The Type to get the Type of collection, it passed as a parameter to formJson () method, to parse the JSON string for collection.
While Gson can turn any Java object into a JSON string, parsing the string into a specified collection type takes a little effort because of the generics involved — TypeToken is the silver bullet to solve this problem.
For Gson, let’s leave it there and talk about it when we have a chance.
03, Jackson
Jackson is an open source Java library for serializing and deserializing JSON based on Stream, with a very active community and fast updates.
- As of now, GitHub has a 5.2K star;
- Spring MVC’s default JSON parser;
- Jackson is faster at parsing large JSON files than Gson.
- Jackson is more stable than Fastjson.
Before using Jackson, you need to add Jackson dependencies.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.1</version>
</dependency>
Copy the code
Jackson’s core module consists of three parts.
- Jackson-core, the core package, provides related apis based on “stream mode” parsing, including JsonPaser and JsonGenerator.
- Annotations jackson-Annotations, a package, provide standard annotations.
- Jackson-databind, a data binding package that provides apis based on “object binding” resolution (ObjectMapper) and “tree model” resolution (JsonNode); The API based on “object binding” parsing and the API based on “tree model” parsing rely on the API based on “stream pattern” parsing.
When jackson-Databind was added, Jackson-core and Jackson-Annotations were added to the Java project.
An IDEA plugin, JsonFormat, can generate a JavaBean from a JSON string. How do you use it? Create a new class and bring up the Generate menu.
Select JsonFormat and enter the JSON string.
{
"age" : 18.
"name" : "Silent King II."
}
Copy the code
After confirmation, the JavaBean is generated, as shown in the following figure.
public class Cmower {
private Integer age;
private String name;
public Cmower(a) {
}
public Cmower(Integer age, String name) {
this.age = age;
this.name = name;
}
public Integer getAge(a) {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Copy the code
So how do you use Jackson? As mentioned earlier, ObjectMapper is Jackson’s most commonly used API, so let’s look at a simple example.
Cmower wanger = new Cmower(18."Silent King II.");
System.out.println(wanger);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(wanger);
System.out.println(jsonString);
Cmower deserialize = mapper.readValue(jsonString,Cmower.class);
System.out.println(deserialize);
Copy the code
ObjectMapper serializes Java objects into JSON and stores JSON in different formats through a series of methods called writeValue().
- String (writeValueAsString)
- Byte Array (writeValueAsBytes)
ObjectMapper deserializes (parses) JSON into Java objects from different data sources (String, Bytes) using the readValue() family of methods.
The output result of the program is:
com.cmower.java_demo.jackson.Cmower@214c265e
{
"age18, ":
"name":" Silent King II"
}
com.cmower.java_demo.jackson.Cmower@612fc6eb
Copy the code
Before calling the writeValue() or readValue() methods, you often need to do some custom configuration between JSON and Javabeans.
1) Ignore fields that exist in JSON but do not exist in Javabeans during deserialization
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Copy the code
2) Ignore null fields during serialization
apper.setSerializationInclusion(Include.NON_NULL);
Copy the code
In some cases, these custom configurations play an important role in converting between JSON and Javabeans. For more configuration information, look at the Javadoc for DeserializationFeature, SerializationFeature, and Include classes.
So let’s stop there and talk about Jackson when we get a chance.
04, org. Json
Json org.json is an open source library provided by JSON, but it can be a bit cumbersome to use.
Before you can use org.json, you need to introduce org.json dependencies into your project.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>
Copy the code
The org.json.JSONObject class parses a JSON string into a Java object using the new keyword, and then gets the corresponding key value using the series of methods of GET, as shown in the following code example.
String str = "{\"name\ : \" Silent King 2 \", \"age\ : 18}";
JSONObject obj = new JSONObject(str);
String name = obj.getString("name");
int age = obj.getInt("age");
Copy the code
The org.json.jsonArray () method of the org.json.jsonObject class returns an org.json.jsonArray object representing an array, and then loops through the elements of the array, as shown in the following code example.
String str = "{ \"number\": [3, 4, 5, 6] }";
JSONObject obj = new JSONObject(str);
JSONArray arr = obj.getJSONArray("number");
for (int i = 0; i < arr.length(); i++) {
System.out.println(arr.getInt(i));
}
Copy the code
To get a JSON string, you can use the put() method to put key-value pairs into org.json.jsonObject and then call the toString() method, as shown in the code example below.
JSONObject obj = new JSONObject();
obj.put("name"."Silent King II.");
obj.put("age".18);
System.out.println(obj.toString()); // {"name":" age":18}
Copy the code
Json is far less flexible and apI-rich than Gson and Jackson.
05, fastjson
Fastjson is alibaba’s open source JSON parsing library, which can parse JSON-formatted strings and also supports serialization of Java beans into JSON strings.
Compared with other JSON libraries, FastJSON is fast and its API is very simple to use. It was selected as one of the most popular domestic open source software by Open Source China in 2012.
PS: While Fastjson is reliable, it has had its fair share of incidents, which I won’t mention here.
Before you can use Fastjson, you need to add fastjson dependencies.
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.61</version>
</dependency>
Copy the code
So how do you use Fastjson? Let’s create a Java Bean with three fields: age, name, name, and list books.
class Cmower1 {
private Integer age;
private String name;
private List<String> books = new ArrayList<>();
public Cmower1(Integer age, String name) {
this.age = age;
this.name = name;
}
// getter/setter
public void putBook(String bookname) {
this.books.add(bookname);
}
}
Copy the code
We then serialize the Java object to a JSON string using json.tojsonString (), as shown in the following code:
Cmower1 cmower = new Cmower1(18."Silent King II.");
cmower.putBook("The Road to Full Stack Development for the Web");
String jsonString = JSON.toJSONString(cmower);
System.out.println(jsonString);
Copy the code
Program output:
{"age":18."books": ["The Road to Full Stack Development for the Web"]."name":"Silent King II."}
Copy the code
So how do you parse a JSON string? Using the json.parseObject () method, the code example is shown below.
JSON.parseObject(jsonString, Cmower1.class)
Copy the code
06,
Personally, I prefer Gson. After all, it is made by Google, its quality is reliable, and the key is that it really works well.
Jackson, on the other hand, is faster at parsing large JSON files and more stable than FastJSON.
Fastjson, as the pride of our homegrown open-source software, is, well, respectable.
To my surprise, org.json was the top answer to a 1.6 million page view question on StackOverflow. To my surprise, my boss also chose org.json, saying it was a native, json’s official son.
I…
07, thanks
Well, readers, that’s all for this article. Can see here are the most excellent programmers, promotion pay is you 👍. If you don’t like it and want to see more, I recommend one more article.
There is still a week to liberate, inadvertently lu code, anxious to go home
Original is not easy, if you feel a little use, please don’t be stingy with your hands like the power; If you want to see the second brother’s updated article for the first time, please scan the qr code below and follow the official account of Silent King ii. See you in the next article!