Java - Jackson JSON Java Parser API

网友投稿 955 2022-05-30

文章目录

概述

依赖

Jackson JSON示例

基础数据

JSON转换为Java对象

Jackson JSON –将JSON转换为Map

概述

Jackson JSON Java Parser非常流行,并且也用于Spring框架。

Jackson JSON Parser API提供了将JSON转换为POJO对象的简便方法,并支持从JSON数据轻松转换为Map。

Jackson也支持泛型,并直接将它们从JSON转换为对象。

依赖

要在我们的项目中使用Jackson JSON Java API,我们可以将其添加到项目构建路径中

com.fasterxml.jackson.core jackson-databind 2.2.3

1

2

3

4

5

jackson-databind jar依赖于jackson-core和jackson-annotations库,因此,如果直接将它们添加到构建路径,请确保将所有三个添加在一起,否则会出现运行时错误。

Jackson JSON示例

基础数据

对于从JSON到POJO / Java对象转换的示例,我们将使用一个嵌套对象和数组的复杂示例。、

我们将在Java对象中使用数组,列表和Map进行转换。 json存储在文件employee.txt中,其结构如下

{ "id": 123, "name": "Pankaj", "permanent": true, "address": { "street": "Albany Dr", "city": "San Jose", "zipcode": 95129 }, "phoneNumbers": [ 123456, 987654 ], "role": "Manager", "cities": [ "Los Angeles", "New York" ], "properties": { "age": "29 years", "salary": "1000 USD" } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

有以下与json数据相对应的java类。

【Address 】

public class Address { private String street; private String city; private int zipcode; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getZipcode() { return zipcode; } public void setZipcode(int zipcode) { this.zipcode = zipcode; } @Override public String toString(){ return getStreet() + ", "+getCity()+", "+getZipcode(); }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

【Employee 】

import java.util.Arrays; import java.util.List; import java.util.Map; public class Employee { private int id; private String name; private boolean permanent; private Address address; private long[] phoneNumbers; private String role; private List cities; private Map properties; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isPermanent() { return permanent; } public void setPermanent(boolean permanent) { this.permanent = permanent; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public long[] getPhoneNumbers() { return phoneNumbers; } public void setPhoneNumbers(long[] phoneNumbers) { this.phoneNumbers = phoneNumbers; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public List getCities() { return cities; } public void setCities(List cities) { this.cities = cities; } public Map getProperties() { return properties; } public void setProperties(Map properties) { this.properties = properties; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("***** Employee Details *****\n"); sb.append("ID="+getId()+"\n"); sb.append("Name="+getName()+"\n"); sb.append("Permanent="+isPermanent()+"\n"); sb.append("Role="+getRole()+"\n"); sb.append("Phone Numbers="+Arrays.toString(getPhoneNumbers())+"\n"); sb.append("Address="+getAddress()+"\n"); sb.append("Cities="+Arrays.toString(getCities().toArray())+"\n"); sb.append("Properties="+getProperties()+"\n"); sb.append("*****************************"); return sb.toString(); } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

Employee是代表根json对象的Java bean。现在,让我们看看如何使用Jackson JSON解析器API将JSON转换为Java对象

JSON转换为Java对象

import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.ObjectNode; import com.journaldev.jackson.model.Address; import com.journaldev.jackson.model.Employee; public class JacksonObjectMapperExample { public static void main(String[] args) throws IOException { //read json file data to String byte[] jsonData = Files.readAllBytes(Paths.get("employee.txt")); //create ObjectMapper instance ObjectMapper objectMapper = new ObjectMapper(); //convert json string to object Employee emp = objectMapper.readValue(jsonData, Employee.class); System.out.println("Employee Object\n"+emp); //convert Object to json string Employee emp1 = createEmployee(); //configure Object mapper for pretty print objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); //writing to console, can write to any output stream such as file StringWriter stringEmp = new StringWriter(); objectMapper.writeValue(stringEmp, emp1); System.out.println("Employee JSON is\n"+stringEmp); } public static Employee createEmployee() { Employee emp = new Employee(); emp.setId(100); emp.setName("David"); emp.setPermanent(false); emp.setPhoneNumbers(new long[] { 123456, 987654 }); emp.setRole("Manager"); Address add = new Address(); add.setCity("Bangalore"); add.setStreet("BTM 1st Stage"); add.setZipcode(560100); emp.setAddress(add); List cities = new ArrayList(); cities.add("Los Angeles"); cities.add("New York"); emp.setCities(cities); Map props = new HashMap(); props.put("salary", "1000 Rs"); props.put("age", "28 years"); emp.setProperties(props); return emp; } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

Java - Jackson JSON Java Parser API

72

73

74

75

输出

Employee Object ***** Employee Details ***** ID=123 Name=Pankaj Permanent=true Role=Manager Phone Numbers=[123456, 987654] Address=Albany Dr, San Jose, 95129 Cities=[Los Angeles, New York] Properties={age=29 years, salary=1000 USD} ***************************** Employee JSON is //printing same as above json file data

1

2

3

4

5

6

7

8

9

10

11

12

13

com.fasterxml.jackson.databind.ObjectMapper是Jackson API中最重要的类,它提供readValue()和writeValue()方法以将JSON转换为Java Object以及将Java Object转换为JSON。

ObjectMapper类可以重用,并且可以将其作为Singleton对象初始化一次。有很多重载版本的readValue()和writeValue()方法可用于字节数组,File,输入/输出流和Reader / Writer对象。

Jackson JSON –将JSON转换为Map

在data.txt文件中有一个如下所示的JSON对象:

{ "name": "David", "role": "Manager", "city": "Los Angeles" }

1

2

3

4

5

2.2 Jackson JSON –读取特定的JSON密钥

2.3 Jackson JSON –编辑JSON文档

2.4 Jackson JSON流API示例

API Java JSON

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:使用 perl-support.vim 插件使 Vim 成为你的 Perl IDE
下一篇:ROS1和ROS2如何选?(机器人操作系统2021)ROS2极简总结-新增概念
相关文章