preface
In the work, it is necessary to Json parsing processing, generally we commonly use FastJson, Jackson, Gson these three tool classes, they have their own advantages and disadvantages, this article we use their RESPECTIVE API, comparison.
A brief introduction of each JSON technology
1.1 FastJson role
Fastjson is Alibaba’s open source JSON parsing library, which can parse JSON-formatted strings and support serialization of Java beans to JSON strings, as well as deserialization from JSON strings to Javabeans.
Github website: github.com/alibaba/fas…
1.2 Jackson role
Jackson has been called the “Java JSON library” or “Java’s best JSON parser.” Or “JSON for Java” for short.
Github website: github.com/FasterXML/j…
1.3 Gson role
Gson is a Java library that can be used to transform Java objects into their JSON representation. It can also be used to convert JSON strings into equivalent Java objects. Gson can work with any Java object, including pre-existing objects for which you have no source code.
Github website: github.com/google/gson
Two, the use of steps
2.1 import library
FastJson dependencies
<! -- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
Copy the code
The Maven central repository: mvnrepository.com/artifact/co…
2, Jackson dependence
<! -- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.1</version>
</dependency>
Copy the code
The Maven central repository: mvnrepository.com/artifact/co…
3. Gson dependency
<! -- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
Copy the code
The Maven central repository: mvnrepository.com/artifact/co…
2.2 Converting JSON Strings into Java objects
Person object
/ * * *@authorDT developer */
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
public class Person implements Serializable {
private Integer id;
private String name;
private Date createTime;
}
Copy the code
FastJson version
public static void main(String[] args) {
String json = "{\"createTime\":1621341922450,\"id\":1,\"name\":\"DT\"}";
Method 1: Convert the JSON string into a Java object
Person person = JSON.parseObject(json,Person.class);
System.out.println("Java object - > > >"+person);
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
// Method 2: Convert json strings into Java objects
Person newPerson2 = JSONObject.parseObject(json, Person.class);
System.out.println("Java object - > > >"+newPerson2);
}
Copy the code
JSON.parseObject(String,Object.class)
JSONObject.parseObject(String, Object.class)
Copy the code
2. Jackson version
public static void main(String[] args) {
// Create the Jackson core object ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"createTime\":1621341922450,\"id\":1,\"name\":\"DT\"}";
try {
Person person = objectMapper.readValue(json, Person.class);
System.out.println("Java object - > > >"+person);
} catch(JsonProcessingException e) { e.printStackTrace(); }}Copy the code
3. Gson version
public static void main(String[] args) {
// Gson cannot convert the timestamp to date properly
// Register the Date type using JSON memory tree
final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
return new Date(jsonElement.getAsJsonPrimitive().getAsLong());
}
}).create();
String json = "{\"createTime\":1621341922450,\"id\":1,\"name\":\"DT\"}";
Person person = gson.fromJson(json, Person.class);
System.out.println("Java object - > > >"+person);
}
Copy the code
2.3 Converting Java Objects to JSON Strings
FastJson version
public static void main(String[] args) {
Person person = new Person(1."DT".new Date());
Method 1: Convert the object to a JSON string
String json = JSON.toJSONString(person);
System.out.println("Json string ->>>"+json);
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
Method 2: Convert the object to a JSON string
String json2 = JSONObject.toJSONString(person);
System.out.println("Json string ->>>"+json2);
}
Copy the code
JSONObject.toJSONString(String)
JSON.toJSONString(String)
Copy the code
2. Jackson version
public static void main(String[] args) {
// Create the Jackson core object ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person(1."DT".new Date());
try {
String json = objectMapper.writeValueAsString(person);
System.out.println("Json string ->>>"+json);
} catch(JsonProcessingException e) { e.printStackTrace(); }}Copy the code
3. Gson version
public static void main(String[] args) {
Gson gson = new Gson();
Person person = new Person(1."DT".new Date());
String json = gson.toJson(person);
System.out.println("Json string ->>>"+json);
}
Copy the code
2.4 Converting JSON string arrays to JSON arrays
FastJson version
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person(1."DT".new Date()));
personList.add(new Person(2."DT1".new Date()));
personList.add(new Person(3."DT2".new Date()));
String json = JSONObject.toJSONString(personList);
JSONArray jsArr = JSONObject.parseArray(json);
System.out.println(jsArr);
}
Copy the code
JSONObject.parseArray(json)
Copy the code
Iterating through the loop Json array:
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person(1."DT".new Date()));
personList.add(new Person(2."DT1".new Date()));
personList.add(new Person(3."DT2".new Date()));
String json = JSONObject.toJSONString(personList);
JSONArray jsArr = JSONObject.parseArray(json);
// traversal mode 1
jsArr.stream().forEach(json1 ->{
System.out.println(json1.toString());
});
// traversal mode 2
for (Object o : jsArr) {
JSONObject obj = (JSONObject) o;
System.out.println("Take the id - > > >" + obj.get("id"));
// Check whether key exists
System.out.println("Does key exist ->>>"+obj.containsKey("name1"));
// Determine whether a value exists
System.out.println("Does value exist ->>>"+obj.containsValue(obj.get("id"))); }}Copy the code
2. Jackson version
public static void main(String[] args) throws JsonProcessingException {
// Convert a JSON array to an array object
ObjectMapper mapper = new ObjectMapper();
String json = "[{\ \" id ": 1, \" name \ ": \" zhang SAN \ ", \ "createTime \" : 1622719597081}, {\ \ "id" : 2, \ "name \" : \ "li si \", \ "createTime \" : 1622719597081}]";
1 / / way
Person[] pp1 = mapper.readValue(json, Person[].class);
for (Person person : pp1) {
System.out.println(person);
}
2 / / way
List<Person> ppl2 = Arrays.asList(mapper.readValue(json, Person[].class));
ppl2.stream().forEach(System.out::println);
3 / / way
List<Person> pp3 = mapper.readValue(json, new TypeReference<List<Person>>() {});
pp3.stream().forEach(System.out::println);
}
Copy the code
3. Gson version
` ` `java
public static void main(String[] args) {
// Gson cannot convert the timestamp to date properly
// Register the Date type using JSON memory tree
final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
return new Date(jsonElement.getAsJsonPrimitive().getAsLong());
}
}).create();
String json = "[{\ \" id ": 1, \" name \ ": \" zhang SAN \ ", \ "createTime \" : 1622719597081}, {\ \ "id" : 2, \ "name \" : \ "li si \", \ "createTime \" : 1622719597081}]";
Type type = new TypeToken<ArrayList<Person>>(){}.getType();
List<Person> personList = gson.fromJson(json, type);
personList.stream().forEach(System.out::println);
}
Copy the code
When a List is deserialized, it must provide its Type, and the Type of the current List can be defined through the typetoken.getType () method provided by Gson.
2.5 Converting a JSON Array to a JSON String
FastJson version
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person(1."DT".new Date()));
personList.add(new Person(2."DT1".new Date()));
personList.add(new Person(3."DT2".new Date()));
String json = JSONObject.toJSONString(personList);
System.out.println("json->>>"+json);
}
Copy the code
2. Jackson version
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
List<Person> personList = new ArrayList<>();
personList.add(new Person(1."DT".new Date()));
personList.add(new Person(2."DT1".new Date()));
personList.add(new Person(3."DT2".new Date()));
String json = objectMapper.writeValueAsString(personList);
System.out.println("json->>>"+json);
}
Copy the code
3. Gson version
public static void main(String[] args) {
Gson gson = new Gson();
List<Person> personList = new ArrayList<>();
personList.add(new Person(1."DT".new Date()));
personList.add(new Person(2."DT1".new Date()));
personList.add(new Person(3."DT2".new Date()));
String json = gson.toJson(personList);
System.out.println("json->>>"+json);
}
Copy the code
conclusion
Above is today’s content, can stick to see here, you will have a harvest, personally, I prefer to use FastJson pushing tutorial document: www.runoob.com/w3cnote/fas…
Liking is an attitude, persistence is the embodiment of attitude.