`

Jackson实现Object对象与Json字符串的互转

阅读更多

        在项目开发过程中,当客户端与服务器响应时,数据交互是必不可少的。然而通过Json实现数据交互成为我们开发中的一部分,进而Jackson为我们的Json转化提供了很好的机制。下面我将利用实例总结如何使用jackson。

一.准备

        如果你需要使用jackson,你必须得导入相应的架包,有如下三个包jackson-annotations;jackson-core;jackson-databind。

 

二.不带日期的对象实体与json互转

1.定义实体UserBean.java、DeptBean.java

package com.bijian.study;

public class UserBean {
    
    private int userId;
    private String userName;
    private String password;
    private String email;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "UserBean [userId=" + userId + ", userName=" + userName + ", password=" + password + ", email=" + email
                + "]";
    }

    public UserBean(int userId, String userName, String password, String email) {
        super();
        this.userId = userId;
        this.userName = userName;
        this.password = password;
        this.email = email;
    }

    public UserBean() {
        super();
    }
}
package com.bijian.study;

import java.util.List;

public class DeptBean {
    
    private int deptId;
    private String deptName;
    private List<UserBean> userBeanList;

    public int getDeptId() {
        return deptId;
    }

    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    public List<UserBean> getUserBeanList() {
        return userBeanList;
    }

    public void setUserBeanList(List<UserBean> userBeanList) {
        this.userBeanList = userBeanList;
    }

    @Override
    public String toString() {
        
        String userBeanListString = "";
        for (UserBean userBean : userBeanList) {
            userBeanListString += userBean.toString() + "\n";
        }

        return "DeptBean [deptId=" + deptId + ", deptName=" + deptName + ", \nuserBeanListString=" + userBeanListString
                + "]";
    }

    public DeptBean(int deptId, String deptName, List<UserBean> userBeanList) {
        super();
        this.deptId = deptId;
        this.deptName = deptName;
        this.userBeanList = userBeanList;
    }

    public DeptBean() {
        super();
    }
}

        注意:在实体中必须存在无参的构造方法,否则转换时会有如下异常:

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.jackson.bean.UserBean]: can not instantiate from JSON object (need to add/enable type information?)

 

2.jackson数据转换工具类

package com.bijian.study;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * The class JacksonUtil
 * 使用泛型方法,把json字符串转换为相应的JavaBean对象。
 * (1)转换为普通JavaBean:readValue(json,Student.class)
 * (2)转换为List,如List<Student>,将第二个参数传递为Student[].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
 *
 * json字符与对像转换
 */
public final class JacksonUtil {

    public static ObjectMapper objectMapper;

    /**
     * json对象转JAVA对象
     * 
     * @param jsonStr
     * @param valueType
     * @return
     */
    public static <T> T readValue(String jsonStr, Class<T> valueType) {

        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        try {
            return objectMapper.readValue(jsonStr, valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * json数组转List
     * @param jsonStr
     * @param valueTypeRef
     * @return
     */
    public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef) {

        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        try {
            return objectMapper.readValue(jsonStr, valueTypeRef);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 把JavaBean转换为json字符串
     * 
     * @param object
     * @return
     */
    public static String toJSon(Object object) {

        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

 

3.jackson数据转换具体实现

package com.bijian.study;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;

/**
 * 实例实现利用jackson实现实体对象与json字符串的互相转换
 */
public class JacksonDemo {
    
    public static void main(String[] args) {

        UserBean userBean1 = new UserBean(1, "liubei", "123", "liubei@163.com");
        UserBean userBean2 = new UserBean(2, "guanyu", "123", "guanyu@163.com");
        UserBean userBean3 = new UserBean(3, "zhangfei", "123", "zhangfei@163.com");

        List<UserBean> userBeans = new ArrayList<>();
        userBeans.add(userBean1);
        userBeans.add(userBean2);
        userBeans.add(userBean3);

        DeptBean deptBean = new DeptBean(1, "sanguo", userBeans);
        //对象转json
        String userBeanToJson = JacksonUtil.toJSon(userBean1);
        String deptBeanToJson = JacksonUtil.toJSon(deptBean);

        System.out.println("deptBean to json:" + deptBeanToJson);
        System.out.println("userBean to json:" + userBeanToJson);

        //json 转实体对象
        UserBean jsonToUserBean = JacksonUtil.readValue(userBeanToJson, UserBean.class);
        DeptBean jsonToDeptBean = JacksonUtil.readValue(deptBeanToJson, DeptBean.class);

        System.out.println("json to DeptBean:" + jsonToDeptBean.toString());
        System.out.println("json to UserBean:" + jsonToUserBean.toString());

        //List 转json字符串
        String listToJson = JacksonUtil.toJSon(userBeans);
        System.out.println("list to json:" + listToJson);

        //数组json转 List
        List<UserBean> jsonToUserBeans = JacksonUtil.readValue(listToJson, new TypeReference<List<UserBean>>() {});
        String userBeanString = "";
        for (UserBean userBean : jsonToUserBeans) {
            userBeanString += userBean.toString() + "\n";
        }
        System.out.println("json to userBeans:" + userBeanString);
    }
}

        运行结果:

deptBean to json:{"deptId":1,"deptName":"sanguo","userBeanList":[{"userId":1,"userName":"liubei","password":"123","email":"liubei@163.com"},{"userId":2,"userName":"guanyu","password":"123","email":"guanyu@163.com"},{"userId":3,"userName":"zhangfei","password":"123","email":"zhangfei@163.com"}]}
userBean to json:{"userId":1,"userName":"liubei","password":"123","email":"liubei@163.com"}
json to DeptBean:DeptBean [deptId=1, deptName=sanguo, 
userBeanListString=UserBean [userId=1, userName=liubei, password=123, email=liubei@163.com]
UserBean [userId=2, userName=guanyu, password=123, email=guanyu@163.com]
UserBean [userId=3, userName=zhangfei, password=123, email=zhangfei@163.com]
]
json to UserBean:UserBean [userId=1, userName=liubei, password=123, email=liubei@163.com]
list to json:[{"userId":1,"userName":"liubei","password":"123","email":"liubei@163.com"},{"userId":2,"userName":"guanyu","password":"123","email":"guanyu@163.com"},{"userId":3,"userName":"zhangfei","password":"123","email":"zhangfei@163.com"}]
json to userBeans:UserBean [userId=1, userName=liubei, password=123, email=liubei@163.com]
UserBean [userId=2, userName=guanyu, password=123, email=guanyu@163.com]
UserBean [userId=3, userName=zhangfei, password=123, email=zhangfei@163.com]

 

三.带日期的实体对象与json转换

        jackson实现带日期的实体对象与json转换有两种方法

        1).将实体对象中的日期对象定义为String型,在使用的时候再将String型转换为Date型使用,其他就无需修改。

        2).当实体对象中的日期对象定义为Date型,就需要通过集成JsonSerializer<Date>对象完成日期的转换,本段将重点讲解。

1.在UserBean.java和DeptBean.java中分别添加Date createDate,并加上@JsonSerialize(using = JsonDateFormatFull.class)注解

package com.bijian.study;

import java.util.Date;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

public class UserBean {
    
    private int userId;
    
    private String userName;
    
    private String password;
    
    private String email;
    
    @JsonSerialize(using = JsonDateFormatFull.class)
    private Date createDate;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    @Override
    public String toString() {
        return "UserBean [userId=" + userId + ", userName=" + userName + ", password=" + password + ", email=" + email + ", createDate=" + createDate
                + "]";
    }

    public UserBean(int userId, String userName, String password, String email) {
        super();
        this.userId = userId;
        this.userName = userName;
        this.password = password;
        this.email = email;
    }

    public UserBean() {
        super();
    }
}
package com.bijian.study;

import java.util.Date;
import java.util.List;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

public class DeptBean {
    
    private int deptId;
    
    private String deptName;
    
    @JsonSerialize(using = JsonDateFormatFull.class)
    private Date createDate;
    
    private List<UserBean> userBeanList;

    public int getDeptId() {
        return deptId;
    }

    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
    
    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public List<UserBean> getUserBeanList() {
        return userBeanList;
    }

    public void setUserBeanList(List<UserBean> userBeanList) {
        this.userBeanList = userBeanList;
    }

    @Override
    public String toString() {
        String userBeanListString = "";
        for (UserBean userBean : userBeanList) {
            userBeanListString += userBean.toString() + "\n";
        }

        return "DeptBean [deptId=" + deptId + ", deptName=" + deptName + ", createDate=" + createDate + ", \nuserBeanListString=" + userBeanListString
                + "]";
    }

    public DeptBean(int deptId, String deptName, List<UserBean> userBeanList) {
        super();
        this.deptId = deptId;
        this.deptName = deptName;
        this.userBeanList = userBeanList;
    }

    public DeptBean() {
        super();
    }
}

 

2.实现集成于JsonSerializer<Date>对象的工具类

package com.bijian.study;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * jackson日期转换工具类
 */
public class JsonDateFormatFull extends JsonSerializer<Date> {

    /**
     * Jackson支持日期字符串格式
     * "yyyy-MM-dd'T'HH:mm:ss.SSSZ" "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
     * "EEE, dd MMM yyyy HH:mm:ss zzz" "yyyy-MM-dd"
     */
    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        String formattedDate = formatter.format(value);
        jgen.writeString(formattedDate);
    }
}

 

3.jackson日期互转具体实现

package com.bijian.study;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;

/**
 * 利用jackson实现Json与实体对象的互转
 */
public class JacksonDemo {
    
    public static void main(String[] args) {

        UserBean userBean1 = new UserBean(1, "liubei", "123", "liubei@163.com");
        userBean1.setCreateDate(new Date(Calendar.getInstance().getTimeInMillis()));
        UserBean userBean2 = new UserBean(2, "guanyu", "123", "guanyu@163.com");
        userBean2.setCreateDate(new Date(Calendar.getInstance().getTimeInMillis()));
        UserBean userBean3 = new UserBean(3, "zhangfei", "123", "zhangfei@163.com");
        userBean3.setCreateDate(new Date(Calendar.getInstance().getTimeInMillis()));

        List<UserBean> userBeans = new ArrayList<>();
        userBeans.add(userBean1);
        userBeans.add(userBean2);
        userBeans.add(userBean3);

        DeptBean deptBean = new DeptBean(1, "sanguo", userBeans);
        deptBean.setCreateDate(new Date(Calendar.getInstance().getTimeInMillis()));
        //对象 转json
        String userBeanToJson = JacksonUtil.toJSon(userBean1);
        String deptBeanToJson = JacksonUtil.toJSon(deptBean);

        System.out.println("deptBean to json:" + deptBeanToJson);
        System.out.println("userBean to json:" + userBeanToJson);

        //json 转实体对象
        UserBean jsonToUserBean = JacksonUtil.readValue(userBeanToJson, UserBean.class);
        DeptBean jsonToDeptBean = JacksonUtil.readValue(deptBeanToJson, DeptBean.class);

        System.out.println("json to DeptBean:" + jsonToDeptBean.toString());
        System.out.println("json to UserBean:" + jsonToUserBean.toString());

        //List 转json字符串
        String listToJson = JacksonUtil.toJSon(userBeans);
        System.out.println("list to json:" + listToJson);

        //数组json转 List
        List<UserBean> jsonToUserBeans = JacksonUtil.readValue(listToJson, new TypeReference<List<UserBean>>() {});
        String userBeanString = "";
        for (UserBean userBean : jsonToUserBeans) {
            userBeanString += userBean.toString() + "\n";
        }
        System.out.println("json to userBeans:" + userBeanString);
    }
}

        运行结果:

deptBean to json:{"deptId":1,"deptName":"sanguo","createDate":"2016-07-11T23:53:46","userBeanList":[{"userId":1,"userName":"liubei","password":"123","email":"liubei@163.com","createDate":"2016-07-11T23:53:46"},{"userId":2,"userName":"guanyu","password":"123","email":"guanyu@163.com","createDate":"2016-07-11T23:53:46"},{"userId":3,"userName":"zhangfei","password":"123","email":"zhangfei@163.com","createDate":"2016-07-11T23:53:46"}]}
userBean to json:{"userId":1,"userName":"liubei","password":"123","email":"liubei@163.com","createDate":"2016-07-11T23:53:46"}
json to DeptBean:DeptBean [deptId=1, deptName=sanguo, createDate=Tue Jul 12 07:53:46 CST 2016, 
userBeanListString=UserBean [userId=1, userName=liubei, password=123, email=liubei@163.com, createDate=Tue Jul 12 07:53:46 CST 2016]
UserBean [userId=2, userName=guanyu, password=123, email=guanyu@163.com, createDate=Tue Jul 12 07:53:46 CST 2016]
UserBean [userId=3, userName=zhangfei, password=123, email=zhangfei@163.com, createDate=Tue Jul 12 07:53:46 CST 2016]
]
json to UserBean:UserBean [userId=1, userName=liubei, password=123, email=liubei@163.com, createDate=Tue Jul 12 07:53:46 CST 2016]
list to json:[{"userId":1,"userName":"liubei","password":"123","email":"liubei@163.com","createDate":"2016-07-11T23:53:46"},{"userId":2,"userName":"guanyu","password":"123","email":"guanyu@163.com","createDate":"2016-07-11T23:53:46"},{"userId":3,"userName":"zhangfei","password":"123","email":"zhangfei@163.com","createDate":"2016-07-11T23:53:46"}]
json to userBeans:UserBean [userId=1, userName=liubei, password=123, email=liubei@163.com, createDate=Tue Jul 12 07:53:46 CST 2016]
UserBean [userId=2, userName=guanyu, password=123, email=guanyu@163.com, createDate=Tue Jul 12 07:53:46 CST 2016]
UserBean [userId=3, userName=zhangfei, password=123, email=zhangfei@163.com, createDate=Tue Jul 12 07:53:46 CST 2016]

 

文章来源:http://www.itnose.net/detail/6199228.html

分享到:
评论

相关推荐

    net.sf.json.JSONObject实现Object对象与Json字符串的互转

    实现Object对象与Json字符串的互转"深入探讨了如何使用`JSONObject`来处理这种转换。 首先,我们需要了解`JSONObject`的基本用法。`JSONObject`可以从一个Java对象创建,也可以解析为一个JSON字符串。例如,我们有...

    java对象转换为json字符串或字符串数组

    在Java开发中,将Java对象转换为JSON字符串或字符串数组是一项常见的任务,特别是在与前端交互、数据存储或者网络传输时。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也...

    使用json-lib将java对象转换成json字符串

    JSON字符串到Java对象的转换通常通过反序列化实现,而Java对象到JSON字符串的转换则称为序列化。 - json-lib库提供了一套API,使得这种转换变得简单。例如,使用`net.sf.json.JSONObject.fromObject()`方法可以将...

    解析Json字符串直接转换为对象(包括多层List集合 嵌套)所用jar包

    现在,我们可以使用Jackson库的`ObjectMapper`类将JSON字符串转换为Java对象: ```java import com.fasterxml.jackson.databind.ObjectMapper; public class JsonParser { public static void main(String[] args...

    java 对象与json字符串互相转换工具类

    Java提供了多种库来实现对象与JSON的互转,如Jackson、Gson、Fastjson等。这里我们将主要讨论这些工具类的使用方法以及它们在处理对象到JSON字符串和反向转换时的关键知识点。 1. Jackson库: Jackson是Java中非常...

    json字符串转成 Map/List

    JSON字符串的结构主要包括对象(键值对的集合,用花括号{}包围)和数组(有序元素的集合,用方括号[]包围)。在Java中,我们可以使用各种库,如Gson、Jackson、org.json等,来完成这个转换。 1. Gson库: Gson是由...

    利用java反射将json字符串转成对象.zip

    在给定的“利用java反射将json字符串转成对象”的主题中,我们将深入探讨如何借助反射机制将JSON字符串转换为Java对象。 首先,我们需要了解JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人...

    (Java)json和String互转必备Jar包

    然而,Java原生并不支持直接将JSON字符串与Java对象进行转换,因此我们需要依赖第三方库来实现这一功能。本资源提供的"(Java)json和String互转必备Jar包"就是为了满足这种需求。 这个Jar包包含了一些关键的API和...

    json字符串转化为list泛型

    在Java编程中,我们经常需要将JSON格式的数据转换为Java对象,这通常涉及到将JSON字符串转化为List泛型。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和...

    JSON字符串和java对象的相互转换

    在Java开发中,JSON字符串与Java对象之间的相互转换是常见的操作,特别是在网络通信、数据存储以及API接口设计等领域。 JSON字符串转Java对象: 在Java中,我们通常使用第三方库如Jackson、Gson、Fastjson等来实现...

    json字符串转换插件

    在Java中,我们通常需要将这样的JSON字符串转换为Java对象,或者将Java对象转换为JSON字符串,以便于数据的序列化和反序列化。 以Gson库为例,它是Google提供的一个强大的JSON处理库。要在项目中使用Gson,首先需要...

    提供将对象转换成JSON字符串的方法 (2).pdf

    在提供的代码片段中,可以看到一个名为`JSON`的公共类,它包含了一些静态方法来实现对象到JSON字符串的转换。以下是这些方法的详细解释: 1. `toJSON(Object obj)`:这个方法接受一个Java对象作为参数,它假设这个...

    Java Web程序实现返回JSON字符串的方法总结

    Java Web 程序实现返回 JSON 字符串的方法总结 Java Web 程序实现返回 JSON 字符串的方法总结是 Java Web 开发中非常重要的一部分。随着 JSON 数据交换格式的广泛应用,Java Web 程序员需要学习如何将 Java 对象...

    java解析Json字符串

    Java解析Json字符串是Java开发中常见的一项任务,特别是在与Web服务交互、数据交换或存储时。Json(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。在Java...

    用于java对象与json对象间的相互转换(net.sf.json.JSONObject)

    `fromObject`方法将Java对象转换为`JSONObject`,然后调用`toString()`将其转化为JSON字符串。 ### 进阶使用 - **处理嵌套结构**:`JSONObject`也支持嵌套结构,即JSON对象内包含其他JSON对象或数组。可以通过递归...

    利用反射实现对象转json格式字符串

    在Java中,我们通常使用Jackson库(`com.fasterxml.jackson.databind.ObjectMapper`)或Google的Gson库来将Java对象转换为JSON字符串。但是,如果我们想通过反射实现这个功能,我们需要遍历对象的所有属性并将其映射...

    ajax json java 用法 json 将List、Object转换为Json格式字符串

    本文中的代码使用了自定义的方法实现对象到 JSON 字符串的转换。 #### 三、代码分析 1. **`objectToJson` 方法**: - 此方法接收一个 `Object` 类型参数,并将其转换为 JSON 字符串。 - 如果传入的对象为 `null`...

    Json与java对象之间相互转换源码

    在Java中,我们经常需要将JSON字符串与Java对象进行相互转换,以便于数据的传输和处理。本篇文章将详细探讨这个过程,以及如何使用常见的Java JSON库,如Gson和Jackson,进行JSON与Java对象的转换。 首先,让我们...

Global site tag (gtag.js) - Google Analytics