JAVA 对象转换为JSON

转载:如何把java对象转换为json java对象怎么转成json_clghxq的技术博客_51CTO博客

1、Java对象列表转换为JSON对象数组,并转为字符串

JSONArray jsonArray = JSONArray.fromObject(list);
String jsonArrayStr = jsonArray.toString();


2、把Java对象转换成JSON对象,并转化为字符串

JSONObject jsonObject = JSONObject.fromObject(obj);
String jsonObjectStr = jsonObject.toString();


3、过滤不需要转换为JSON格式的属性

使用jsonConfig对象的setExcludes()方法,传入参数为待过滤属性组成的数组。

JsonConfig cfg = new JsonConfig();
cfg.setExcludes(new String[] {“待过滤属性1”, “待过滤属性2”, …, “待过滤属性n”});

4. json转bean

JSONObject.toBean(targetJson, targetClass);

5、实例

package com.ajax.test;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
public class Customer {
    public Customer(String name, String id) {
        super();
        this.name = name;
        this.id = id;
    }
    private String name;
    private String id;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public static void main(String[] args) throws JsonProcessingException {
        //包含多个对象的List集合转换为JSON格式
        List<Customer> list = new ArrayList<Customer>();
        Customer c1 = new Customer(“Alice”, “001”);
        Customer c2 = new Customer(“Bruce”, “002”);
        Customer c3 = new Customer(“Cindy”, “003”);
        list.add(c1);
        list.add(c2);
        list.add(c3);
        JsonConfig config1 = new JsonConfig();
        //过滤List集合中的Customer对象的id属性不生成JSON
        config1.setExcludes(new String[] {“id”});
        JSONArray jsonArray = JSONArray.fromObject(list, config1);
        System.out.println(jsonArray.toString());
        //一个对象转换为JSON格式
        Customer c = new Customer(“Boss”, “004”);
        JsonConfig config2 = new JsonConfig();
        //过滤Customer对象的id属性不生成JSON
        config2.setExcludes(new String[] {“id”});
        JSONObject jsonObject = JSONObject.fromObject(c, config2);
        System.out.println(jsonObject.toString());
    }
}

6.将父类对象转化为子类对象:

创建父类实例,将父类实例化

将子类实例转化成json

将父类实例转化成json

遍历父类json实例,使用子类json获取vaule值,设置到父类json中。

代码如下:

public static Object createBeanWith(Class targetClass, Object source) {
        Object target = null;
        try {
            target = targetClass.newInstance();
        } catch (Exception e) {
            return null;
        }
        JSONObject targetJson = JSONObject.fromObject(target);
        JSONObject sourceJson = JSONObject.fromObject(source);
        for (Object key : targetJson.keySet()) {
            if (sourceJson.containsKey(key)) {
                targetJson.put(key, sourceJson.get(key));
            }
        }
        return JSONObject.toBean(targetJson, targetClass);
    }

精简写法:

Object result = JSONObject.parseObject(JSONObject.toJSONString(source), targetClass);

maven依赖的包:

<!--JSON-->
<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20230227</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
<dependency>
    <groupId>net.sf.ezmorph</groupId>
    <artifactId>ezmorph</artifactId>
    <version>1.0.6</version>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

<!--用于解析json-->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

7、使用hutool工具类

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
public static Object createBeanWith(Class targetClass, Object source) {
        Object target = null;
        try {
            target = targetClass.newInstance();
        } catch (Exception e) {
            return null;
        }
        JSONObject targetJson = JSONUtil.parseObj(target, false);
        JSONObject sourceJson = JSONUtil.parseObj(source, false);
        for (String key : targetJson.keySet()) {
            if (sourceJson.containsKey(key)) {
                targetJson.set(key, sourceJson.get(key));
            }
        }
        return JSONUtil.toBean(targetJson, targetClass);
    }

8、 使用Spring类的方法:

/**
 * 这种方式是用了Spring的工具类, 不关乎是否有继承关系,
 * 只要有相同的属性就会拷贝进去
 */
Foo foo = new Foo();
Son son = new Son();
BeanUtils.copyProperties(foo, son);

参考:

父类转换成子类, 或者是类之间属性拷贝_父类对象转换为子类对象_孔先生在吗的博客-CSDN博客

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年12月15日
下一篇 2023年12月15日

相关推荐