Java中對json的轉換

一、轉map

使用JSONArray.parseObject方法

引入包:import com.alibaba.fastjson.JSONArray;    及    import java.util.Map;

json格式如下:(DB中的存儲形式)

{
    "size":"XL",
    "color":"臧紅",
    "material":"純棉",
    "colorCode":"1006",
    "styleCode":"553682"
}

代碼轉換

@Test
    public void testTransform() {
        String jsonMap = "{\n" +
                "\t\"size\": \"XL\",\n" +
                "\t\"color\": \"臧紅\",\n" +
                "\t\"colorCode\": \"1006\",\n" +
                "\t\"styleCode\": \"553682\",\n" +
                "\t\"material\": \"純棉\"\n" +
                "}";
        Map mapTypes = JSONArray.parseObject(jsonMap);
        String size = mapTypes.get("size") != null ? mapTypes.get("size").toString() : "";
        String color = mapTypes.get("color") != null ? mapTypes.get("color").toString() : "";
        String colorCode = mapTypes.get("colorCode") != null ? mapTypes.get("colorCode").toString() : "";
        String styleCode = mapTypes.get("styleCode") != null ? mapTypes.get("styleCode").toString() : "";
        String material = mapTypes.get("material") != null ? mapTypes.get("material").toString() : "";

        System.out.println("-----------【Start】測試打印-------------");
        System.out.println("尺寸:" + size + ";顏色:" + color + ";顏色號碼:" + colorCode + ";款式編碼:" + styleCode + ";材質:" + material);
        System.out.println("-----------【END】測試打印-------------");

    }

打印:

二、轉list

第一步:定義一個list的json

數據庫定義如下:ALTER TABLE people ADD `student` json DEFAULT NULL COMMENT '學生信息';

第二步:定義與之對應的對象

package Entity;


import java.util.List;

/**
 * @autor Star
 * @date 2020-03-03 14:37
 */
public class Student {
    private String name;
    private String number;
    private List<String> hobby;

    public String getName() {
        return name;
    }

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

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public List<String> getHobby() {
        return hobby;
    }

    public void setHobby(List<String> hobby) {
        this.hobby = hobby;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", number='" + number + '\'' +
                ", hobby=" + hobby +
                '}';
    }
}

第三步:自己實現轉換的工具

maven引入依賴

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.3</version>
        </dependency>

轉換工具

package common;

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

/**
 * @autor Star
 * @date 2020-03-03 14:21
 */
public class JacksonUtils {
    private final static ObjectMapper om = new ObjectMapper();
    public static <T> T fromJson(String content, TypeReference typeReference) {
        try {
            return om.readValue(content, typeReference);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

第四步:測試

import Entity.Student;
import com.fasterxml.jackson.core.type.TypeReference;
import common.JacksonUtils;
import org.junit.Test;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @autor Star
 * @date 2020-03-03 14:34
 */
public class TestJsonTransform {

    @Test
    public void TestJsonToList() {
        String json="[\n" +
                "\t{\n" +
                "\t\t\"name\": \"張傑\",\n" +
                "\t\t\"number\": \"20201108\",\n" +
                "\t\t\"hobby\": [\"打籃球\",\"唱歌\",\"跳舞\"]\n" +
                "\t},{\n" +
                "\t\t\"name\": \"謝娜\",\n" +
                "\t\t\"number\": \"20201109\",\n" +
                "\t\t\"hobby\": [\"主持\",\"表演\",\"跳舞\"]\n" +
                "\t}\n" +
                "]";

        List<Student> strList = JacksonUtils.fromJson(json,new TypeReference<List<Student>>(){});
        if(CollectionUtils.isEmpty(strList)){
            System.out.println("json爲空");
        }
        System.out.println(strList);
    }
}

打印:

 

三、總結

1、如果處理的業務比較複雜,向DB中存儲的時候需要json進行存儲,那麼對數據處理的時候,就存在json轉對象,轉map和list非常常見,先記錄在這。

2、在寫代碼的時候要引入用到的包以及相應的maven依賴。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章