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