让我们看看如何使用Jackson Java JSON Processor将Java对象转换为JSON,反之亦然。 我们可以从Jackson下载页面下载jackson-all-1.6.4.jar。
进行编组和解组的关键类是org.codehaus.jackson.map.ObjectMapper 。
让我们创建一个User java bean,如下所示:
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
}
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
}
现在让我们创建一个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);
这将以JSON格式将用户数据打印为:
{
“ userId”:“ 1”,
“用户名”: { “名字”:“ Katamreddy”, “中间名”:“ Siva”, “姓氏”:“ PrasadReddy” }, “ dob”:1300878089906 }
现在,让我们将json格式的以下用户数据编组为User Object:
{
“ userId”:“ 100”,
“用户名”: { “ firstname”:“ K”, “中间名”:“ Siva”, “ lastname”:“ Prasad” }, “ dob”:1300878089906 }
String userDataJSON =
"{\"userId\":\"100\",\"userName\":{\"firstname\":\"K\""+
",\"middlename\":\"Siva\",\"lastname\":\"Prasad\"},\"dob\":1300878089906}";
User userFromJSON = mapper.readValue(userDataJSON, User.class);
System.out.println(userFromJSON);
这会将User对象打印为:
用户[dob = 3月23日星期三16:31:29 IST 2011,userId = 100,userName = UserName [firstname = K,lastname = Prasad,middlename = Siva]]
日期值被编组为时间戳,这是默认行为。 如果需要,可以如下更改DateFormat:
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);
然后,用户JSON将为:
{
“ userId”:“ 1”,“ userName”:
{ “名字”:“ Katamreddy”, “中间名”:“ Siva”, “姓氏”:“ PrasadReddy” }, “ dob”:“ 2011年3月23日” }
我们还可以将Java对象作为json编组为文件,如下所示:
mapper.writeValue(new File("user.json"), user);
这将创建文件user.json为:
{
“ userId”:“ 100”,
“用户名”: { “ firstname”:“ K”, “中间名”:“ Siva”, “ lastname”:“ Prasad” }, “ dob”:1300878089906 }
我们可以从user,json构建User对象,如下所示:
User user = mapper.readValue(new File("user.json"), User.class);
参考:来自我们JCG合作伙伴Siva Prasad Reddy的 使用Jackson Java JSON Processor的JSON处理 。
相关文章:
翻译自: https://www.javacodegeeks.com/2011/03/java-json-processing-jackson.html