Jackson 是一个 Java 用来处理 JSON 格式数据的类库
Jackson 是一个 Java 用来处理 JSON 格式数据的类库
[代码] 首先创建一个User对象类 (User.java)
01 |
package com.sivalabs.json;
|
02 |
? ? |
03 |
import java.util.Date;
|
04 |
?? ? |
05 |
public class User {
|
06 |
? private String userId;
|
07 |
? private UserName userName;
|
08 |
? private Date dob;
|
09 |
??? ? |
10 |
? @Override |
11 |
? public String toString(){
|
12 |
?? return "User [dob=" + dob + ", userId=" + userId + ", userName=" + userName + "]" ;
|
13 |
? }
|
14 |
? //setters and getters
|
15 |
??? ? |
16 |
} |
[代码] UserName.java
01 |
package com.sivalabs.json;
|
02 |
? ? |
03 |
public class UserName {
|
04 |
? private String firstname;
|
05 |
? private String middlename;
|
06 |
? private String lastname;
|
07 |
??? ? |
08 |
? @Override |
09 |
? public String toString()
|
10 |
? {
|
11 |
?? return "UserName [firstname=" + firstname +?
|
12 |
?? ", lastname=" + lastname+?
|
13 |
?? ", middlename=" + middlename + "]" ;
|
14 |
? }
|
15 |
? //setters and getters
|
16 |
} |
[代码] [Java]代码
01 |
//接下来创建User实例,并生成JSON数据 |
02 |
? ? |
03 |
ObjectMapper mapper = new ObjectMapper();
|
04 |
?? ? |
05 |
UserName userName = new UserName();
|
06 |
userName.setFirstname( "Katamreddy" );
|
07 |
userName.setMiddlename( "Siva" );
|
08 |
userName.setLastname( "PrasadReddy" );
|
09 |
?? ? |
10 |
User user = new User();
|
11 |
user.setUserId( "1" );
|
12 |
user.setUserName(userName); |
13 |
user.setDob( new Date());
|
14 |
?? ? |
15 |
Writer strWriter = new StringWriter();
|
16 |
mapper.writeValue(strWriter, user); |
17 |
String userDataJSON = strWriter.toString(); |
18 |
System.out.println(userDataJSON); |
[代码] 执行结果
01 |
{ |
02 |
"userId":"1", |
03 |
"userName": |
04 |
{ |
05 |
"firstname":"Katamreddy", |
06 |
"middlename":"Siva", |
07 |
"lastname":"PrasadReddy" |
08 |
}, |
09 |
"dob":1300878089906 |
10 |
} |
[代码] 接下来进行JSON到Java对象的转换
1 |
String userDataJSON =? |
2 |
"{\"userId\":\"100\",\"userName\":{\"firstname\":\"K\"" +
|
3 |
",\"middlename\":\"Siva\",\"lastname\":\"Prasad\"},\"dob\":1300878089906}" ;
|
4 |
User userFromJSON = mapper.readValue(userDataJSON, User. class );
|
5 |
System.out.println(userFromJSON); |
[代码] 时间的格式化处理
1 |
DateFormat dateFormat = new SimpleDateFormat( "MM-dd-yyyy" );
|
2 |
SerializationConfig serConfig = mapper.getSerializationConfig(); |
3 |
serConfig.setDateFormat(dateFormat); |
4 |
DeserializationConfig deserializationConfig = mapper.getDeserializationConfig(); |
5 |
deserializationConfig.setDateFormat(dateFormat); |
6 |
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false ); |
[代码] [Java]代码
1 |
//从文件中读取JSON数据 |
2 |
User user = mapper.readValue( new File( "user.json" ), User. class ); |