SpringBoot默认JSON与对象转换
图
使用SpringBoot框架时,如果没有引入特定的JSON处理工具,可以使用自带的ObjectMapper对象处理实体类和JSON之间的转换,能应对非大量转换的场景

代码示例

实现在不使用三方依赖的情况下实现JSON对象的处理

// 对象转Json数据
new ObjectMapper().writeValueAsString(result);
// Json数据转对象
new ObjectMapper().readValue(json, User.class);

封装为工具类

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * 类和JSON
 */
@Slf4j
public class ObjAndJson {

    /**
     * 对象转JSON字符
     */
    public static <T> String toJson(T obj) {
        try {
            return new ObjectMapper().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("JSON转换异常", e);
        }
        return "{}";
    }

    /**
     * JSON字符转对象
     */
    public static <T> T toObj(String json, Class<T> type) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            // 忽略未知属性,即多余字段,否则会报异常
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return mapper.readValue(json, type);
        } catch (JsonProcessingException e) {
            log.error("JSON转换异常", e);
        }
        return null;
    }

}

直接添加JSON对象

JsonObject json = new JsonObject();
json.addProperty("grant_type", "client_credential");
json.addProperty("appid", "wxbe2c771ca621f869");
json.addProperty("secret", "b6b460c4de6ad06fc77ef0c3dcacda71");
System.out.println(json);

直接提取JSON字符串对象

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String json="{\"translation\":\"你好吗\"}";
//String json="{'translation':'你好吗'}";
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
String fieldValue = jsonObject.get("translation").getAsString();
System.out.println(fieldValue); //你好吗