用 Jackson 来处理 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);

[代码] 执行结果

view sourceprint?

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);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值