在工做中,少不了Json解析處理,通常咱們經常使用的就是FastJson、Jackson、Gson這三大工具類,他們都有各自的優缺點,本篇文章咱們來使用一下他們各自的API,對比一下。html
fastjson是阿里巴巴的開源JSON解析庫,它能夠解析JSON格式的字符串,支持將Java Bean序列化爲JSON字符串,也能夠從JSON字符串反序列化到JavaBean。java
Github官網簡介:github.com/alibaba/fas…git
Jackson被稱爲「 Java JSON庫」或「 Java的最佳JSON解析器」。或簡稱爲「 JSON for Java」。github
Github官網簡介:github.com/FasterXML/j…json
Gson是一個Java庫,可用於將Java對象轉換爲其JSON表示形式。它也能夠用於將JSON字符串轉換爲等效的Java對象。Gson能夠處理任意Java對象,包括您沒有源代碼的預先存在的對象。數組
Github官網簡介:github.com/google/gsonmarkdown
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
複製代碼
Maven中央倉庫:mvnrepository.com/artifact/co…app
<!-- 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>
複製代碼
Maven中央倉庫:mvnrepository.com/artifact/co…ide
<!-- 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>
複製代碼
Maven中央倉庫:mvnrepository.com/artifact/co…工具
Person對象
/** * @author DT開發者 */
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
public class Person implements Serializable {
private Integer id;
private String name;
private Date createTime;
}
複製代碼
public static void main(String[] args) {
String json = "{\"createTime\":1621341922450,\"id\":1,\"name\":\"DT\"}";
// 方式1: 將json字符串轉爲Java對象
Person person = JSON.parseObject(json,Person.class);
System.out.println("java對象->>>"+person);
System.out.println("=========================================================");
// 方式2: 將json字符串轉爲Java對象
Person newPerson2 = JSONObject.parseObject(json, Person.class);
System.out.println("java對象->>>"+newPerson2);
}
複製代碼
JSON.parseObject(String,Object.class)
JSONObject.parseObject(String, Object.class)
複製代碼
public static void main(String[] args) {
// 建立Jackson核心對象 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對象->>>"+person);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
複製代碼
public static void main(String[] args) {
// gson沒法正常將時間戳轉化成date
// 使用JSON內存樹註冊Date類型
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對象->>>"+person);
}
複製代碼
public static void main(String[] args) {
Person person = new Person(1,"DT",new Date());
// 方式1:將對象轉爲json字符串
String json = JSON.toJSONString(person);
System.out.println("json字符串->>>"+json);
System.out.println("=========================================================");
// 方式2:將對象轉爲json字符串
String json2 = JSONObject.toJSONString(person);
System.out.println("json字符串->>>"+json2);
}
複製代碼
JSONObject.toJSONString(String)
JSON.toJSONString(String)
複製代碼
public static void main(String[] args) {
// 建立Jackson核心對象 ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person(1,"DT",new Date());
try {
String json = objectMapper.writeValueAsString(person);
System.out.println("json字符串->>>"+json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
複製代碼
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字符串->>>"+json);
}
複製代碼
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);
}
複製代碼
JSONObject.parseArray(json)
複製代碼
遍歷循環Json數組:
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);
// 遍歷方式1
jsArr.stream().forEach(json1 ->{
System.out.println(json1.toString());
});
// 遍歷方式2
for (Object o : jsArr) {
JSONObject obj = (JSONObject) o;
System.out.println("取到id->>>" + obj.get("id"));
// 判斷是否存在key
System.out.println("key是否存在->>>"+obj.containsKey("name1"));
// 判斷是否存在值
System.out.println("value是否存在->>>"+obj.containsValue(obj.get("id")));
}
}
複製代碼
public static void main(String[] args) throws JsonProcessingException {
// 將JSON數組轉換爲array對象
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"id\":1,\"name\":\"張三\",\"createTime\":1622719597081}, {\"id\":2,\"name\":\"李四\",\"createTime\":1622719597081}]";
// 方式1
Person[] pp1 = mapper.readValue(json, Person[].class);
for (Person person : pp1) {
System.out.println(person);
}
// 方式2
List<Person> ppl2 = Arrays.asList(mapper.readValue(json, Person[].class));
ppl2.stream().forEach(System.out::println);
// 方式3
List<Person> pp3 = mapper.readValue(json, new TypeReference<List<Person>>() {});
pp3.stream().forEach(System.out::println);
}
複製代碼
```java public static void main(String[] args) {
// gson沒法正常將時間戳轉化成date
// 使用JSON內存樹註冊Date類型
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\":\"張三\",\"createTime\":1622719597081}, {\"id\":2,\"name\":\"李四\",\"createTime\":1622719597081}]";
Type type = new TypeToken<ArrayList<Person>>(){}.getType();
List<Person> personList = gson.fromJson(json, type);
personList.stream().forEach(System.out::println);
}
複製代碼
List反序列化時必須提供它的Type,經過Gson提供的TypeToken.getType()方法能夠定義當前List的Type。
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);
}
複製代碼
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);
}
複製代碼
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);
}
複製代碼
以上就是今天的內容,能堅持看到這裏,你必定會有收穫,我我的比較喜歡使用FastJson,推擠教程文檔:www.runoob.com/w3cnote/fas…
技術羣:176251012 喜歡是一種態度,堅持纔是態度的體現。