说明
适合不想引入其他依赖完成JSON对象转换的场景
代码示例
实现在不使用三方依赖的情况下实现JSON对象的处理
// 对象转Json数据
new ObjectMapper().writeValueAsString(result);
// Json数据转对象
new ObjectMapper().readValue(json, User.class);
ObjectMapper与Map
ObjectMapper mapper = new ObjectMapper();
// 对象转JSON字符串
String jsonString = mapper.writeValueAsString(yourObject);
// JSON字符串转Map
Map<String, Object> map = mapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {});
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.convertValue(yourObject, new TypeReference<Map<String, Object>>() {});
// object转map
Map<String, Object> phoneInfoMap = new ObjectMapper().convertValue(phoneInfo, new TypeReference<>() {
});
封装为工具类
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); //你好吗