说明:


01:使用gson进行转换

02:使用fastjson进行转换

03:使用jaskson进行转换

04:下一篇介绍序列化和反序列化,和其效率问题

05:推荐json转实体类,或者map和list

06:小编喜欢使用jackson


一:使用Gson转换:

Gson依赖

<dependency>
   	 <groupId>com.google.code.gson</groupId>
     <artifactId>gson</artifactId>
     <version>2.8.6</version>
</dependency>

01、 string 转 json

说明:json格式的string(类如:接收前端响应的)-- > 实体类

/**
     * 测试下gson
     * json格式的string(类如:接收前端响应的)-- > 实体类
     */
    @Test
    public void gson_onvert01() {
    	
        String result = " {\"name\":\"456\",\"power\":\"学生一号\"}";
        //String result="{name:aaa,power:bbb}";
        Gson gson = new Gson();
        TestVo info = gson.fromJson(result, TestVo.class);
        System.out.println("name:" + info.getName());
        System.out.println("power:" + info.getPower());
    }

效果:

fastjson java对象转换成json字符串 fastjson string转json对象_xml

02、实体类 转 gson

/**
     * gson
     * 实体类 --> gson
     */
    @Test
    public void gson_convert02() {
        TestVo testVo = new TestVo();
        testVo.setName("名称");
        testVo.setPower("黑铁用户");
        Gson gson = new Gson();
        String json = gson.toJson(testVo);
        System.out.println("地址值:" + testVo);
        System.out.println("power:" + testVo.getPower());
    }

效果:

fastjson java对象转换成json字符串 fastjson string转json对象_java_02


二: 使用jackson转换(小编较喜欢):

1、引入依赖

<!--版本控制-->
  <jackson.version>2.11.0</jackson.version>
  
   <!--jackson-->
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-core</artifactId>
	    <version>${jackson.version}</version>
	</dependency>
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-annotations</artifactId>
	    <version>${jackson.version}</version>
	</dependency>
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-databind</artifactId>
	    <version>${jackson.version}</version>
	</dependency>
	<dependency>
	    <groupId>com.fasterxml.jackson.dataformat</groupId>
	    <artifactId>jackson-dataformat-xml</artifactId>
	    <version>${jackson.version}</version>
	</dependency>

2、先封装下提高下效率

说明:其实封装也没啥就是 :先配置好的ObjectMapper

JsonUtil.class

package sqy.util.serialize;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import sqy.util.staticMes.Usual;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;

public class JsonUtil {

    /**
     * 格式化Date,为yyyy-MM-dd HH:mm:ss格式
     */
    public final static DateFormat mfAll = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 格式化Date,为yyyy-MM-dd HH:mm:ss.SSS格式
     */
    public final static DateFormat mfAllMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    /**
     * 获取预先配置好的ObjectMapper
     *
     * @return
     */
    public static ObjectMapper getJsonMapper() {
        ObjectMapper om = new ObjectMapper();
        om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//        om.configure(SerializationFeature.WRITE_NULL_MAP_VALUES,false);
//        om.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS,false);

        //通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
        //Include.Include.ALWAYS 默认
        //Include.NON_DEFAULT 属性为默认值不序列化
        //Include.NON_EMPTY 属性为 " 或者为 NULL 都不序列化
        //Include.NON_NULL 属性为NULL 不序列化
        om.setSerializationInclusion(Include.NON_NULL);
        //日期修改为String格式进行传输
        om.setDateFormat(JsonUtil.mfAllMS);
        //设置时区
        om.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        om.setLocale(Locale.CHINA);
        return om;
    }

    /**
     * 获取预先配置好的ObjectMapper
     *
     * @return
     */
    public static XmlMapper getXmlMapper() {
        XmlMapper mMapper = new XmlMapper();
        mMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        mMapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES);
        mMapper.setSerializationInclusion(Include.NON_NULL);
        mMapper.setDateFormat(Usual.mfAll);
        //设置时区
        mMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        mMapper.setLocale(Locale.CHINA);
        return mMapper;
    }
}

3、string 转 map

/**
     * 测试下jackson
     * json格式的string --> map
     */
    @Test
    public void jackson_convert01() throws JsonProcessingException {
        //String result="{name:aaa,power:bbb}";  ---整个格式会报错
        String result = " {\"name\":\"小白\",\"power\":\"学生一号\"}";
        //JsonUtil.getJsonMapper():就是获取预先配置好的ObjectMapper
        ObjectMapper objectMapper = JsonUtil.getJsonMapper();
        Map map = objectMapper.readValue(result, Map.class);
        System.out.println("name:" + map.get("name"));
        System.out.println("map::" + map);
    }

效果:

fastjson java对象转换成json字符串 fastjson string转json对象_xml_03

4、json 转 List集合

/**
     * jaskson
     * 测 json --> List集合
     */
    @Test
    public void jackson_convert02() throws JsonProcessingException {
//        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
//        HashMap<String, Object> map01= new HashMap<>();
//        HashMap<String, Object> map02= new HashMap<>();
//        map01.put("name","map一号");
//        map01.put("age",18);
//        map02.put("name","map二号");
//        map02.put("age",20);
//        list.add(map01);
//        list.add(map02);

        String stringList="[{\"name\":\"map一号\",\"age\":18},{\"name\":\"map二号\",\"age\":20}]";
        ObjectMapper objectMapper = JsonUtil.getJsonMapper();
        ArrayList<HashMap<String,Object>> list = objectMapper.readValue(stringList, ArrayList.class);
        System.out.println(list);

    }

效果:

fastjson java对象转换成json字符串 fastjson string转json对象_xml_04

5、xml 转 json

小编单独抽出来写了==》

三:使用jackson转换(据说开发最简便):

1、依赖

<!-- fastjson -->
  <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>fastjson</artifactId>
       <version>1.2.68.sec10</version>
   </dependency>

2、json 互转 实体类

/**
     * fastjson
     * json  <-->  实体类
     */
    @Test
    public void fastjson_convert01() {
        TestVo testVo = new TestVo();
        testVo.setName("小白");
        testVo.setPower("超级用户");
        String json01 = JSON.toJSONString(testVo);
        String json02 = JSONObject.toJSONString(testVo);
        System.out.println("json01:" + json01);
        System.out.println("json02:" + json02);
        System.out.println("============================================");
        JSONObject jsonObject = JSON.parseObject(json01);
        System.err.println(jsonObject.get("name"));
        System.err.println(jsonObject.get("power"));
    }

效果:

fastjson java对象转换成json字符串 fastjson string转json对象_xml_05

3、json 转 object

/**
     * fastjson 的 JSONObject
     * 测下json -> object
     * 注意:问题本质为内部类无法实例化,会导致fastjson反序列化失败。
     * 报错:com.alibaba.fastjson.JSONException: create instance error, class sqy.TestJson$User
     */
    @Test
    public void fastjson_convert03() {
        JSONObject json = new JSONObject();
        json.put("power", "超级用户");
        json.put("name", "小白");
        System.out.println(json);
        User vo = json.toJavaObject(User.class);
        System.out.println(vo);
    }

效果:

fastjson java对象转换成json字符串 fastjson string转json对象_json_06

4、List集合 转 json

**
     * fastjson
     * 测 List集合 --> json
     */
    @Test
    public void fastjson_convert04() {
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
        HashMap<String, Object> map01= new HashMap<>();
        HashMap<String, Object> map02= new HashMap<>();
        map01.put("name","map一号");
        map01.put("age",18);
        map02.put("name","map二号");
        map02.put("age",20);
        list.add(map01);
        list.add(map02);
        // list->string->json
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list));
        System.out.println(jsonArray);
        jsonArray.forEach(i->{
            System.out.println(i);
        });
    }

效果:

fastjson java对象转换成json字符串 fastjson string转json对象_java_07

四: 小编的完整测试类:

package sqy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.junit.jupiter.api.Test;
import sqy.util.serialize.JsonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author suqinyi
 * @Date 2021/4/22
 */
public class TestJson {

    class TestVo {
        private String name;
        private String power;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPower() {
            return power;
        }

        public void setPower(String power) {
            this.power = power;
        }
    }


    /**
     * 测试下gson
     * json格式的string(类如:接收前端响应的)-- > 实体类
     */
    @Test
    public void gson_onvert01() {
        String result = " {\"name\":\"456\",\"power\":\"学生一号\"}";
        //String result="{name:aaa,power:bbb}";
        Gson gson = new Gson();
        TestVo info = gson.fromJson(result, TestVo.class);
        System.out.println("name:" + info.getName());
        System.out.println("power:" + info.getPower());
    }

    /**
     * gson
     * 实体类 --> gson
     */
    @Test
    public void gson_convert02() {
        TestVo testVo = new TestVo();
        testVo.setName("名称");
        testVo.setPower("黑铁用户");
        Gson gson = new Gson();
        String json = gson.toJson(testVo);
        System.out.println("地址值:" + testVo);
        System.out.println("power:" + testVo.getPower());
    }



//==========================jackson分界线========================================

    /**
     * 测试下jackson
     * json格式的string --> map
     */
    @Test
    public void jackson_convert01() throws JsonProcessingException {
        //String result="{name:aaa,power:bbb}";  ---整个格式会报错
        String result = " {\"name\":\"小白\",\"power\":\"学生一号\"}";
        ObjectMapper objectMapper = JsonUtil.getJsonMapper();
        Map map = objectMapper.readValue(result, Map.class);
        System.out.println("name:" + map.get("name"));
        System.out.println("map::" + map);
    }

    /**
     * jaskson
     * 测 json --> List集合
     */
    @Test
    public void jackson_convert02() throws JsonProcessingException {
//        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
//        HashMap<String, Object> map01= new HashMap<>();
//        HashMap<String, Object> map02= new HashMap<>();
//        map01.put("name","map一号");
//        map01.put("age",18);
//        map02.put("name","map二号");
//        map02.put("age",20);
//        list.add(map01);
//        list.add(map02);

        String stringList="[{\"name\":\"map一号\",\"age\":18},{\"name\":\"map二号\",\"age\":20}]";
        ObjectMapper objectMapper = JsonUtil.getJsonMapper();
        ArrayList<HashMap<String,Object>> list = objectMapper.readValue(stringList, ArrayList.class);
        System.out.println(list);

    }


    //==========================fastjson分界线========================================
    /**
     * fastjson
     * json  <-->  实体类
     */
    @Test
    public void fastjson_convert01() {
        TestVo testVo = new TestVo();
        testVo.setName("小白");
        testVo.setPower("超级用户");
        String json01 = JSON.toJSONString(testVo);
        String json02 = JSONObject.toJSONString(testVo);
        System.out.println("json01:" + json01);
        System.out.println("json02:" + json02);
        System.out.println("============================================");
        JSONObject jsonObject = JSON.parseObject(json01);
        System.err.println(jsonObject.get("name"));
        System.err.println(jsonObject.get("power"));
    }


    /**
     * fastjson 的 JSONObject
     * 测下json -> object
     * 注意:问题本质为内部类无法实例化,会导致fastjson反序列化失败。
     * 报错:com.alibaba.fastjson.JSONException: create instance error, class sqy.TestJson$User
     */
    @Test
    public void fastjson_convert03() {
        JSONObject json = new JSONObject();
        json.put("power", "超级用户");
        json.put("name", "小白");
        System.out.println(json);
        User vo = json.toJavaObject(User.class);
        System.out.println(vo);
    }

    /**
     * fastjson
     * 测 List集合 --> json
     */
    @Test
    public void fastjson_convert04() {
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
        HashMap<String, Object> map01= new HashMap<>();
        HashMap<String, Object> map02= new HashMap<>();
        map01.put("name","map一号");
        map01.put("age",18);
        map02.put("name","map二号");
        map02.put("age",20);
        list.add(map01);
        list.add(map02);
        // list->string->json
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list));
        System.out.println(jsonArray);
        jsonArray.forEach(i->{
            System.out.println(i);
        });
    }
}

K.O:

fastjson java对象转换成json字符串 fastjson string转json对象_xml_08