【Java】Jsonあれこれ
実装
ライブラリの追加
-
gradle
dependencies {
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.12.3'
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.12.3'
}
シリアライズ(data→Json文字列)
/** Jacksonのオブジェクトマッパー */
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* Jsonのシリアライズ
*
* @param data
* @return
*/
public static <T> String serializeJson(T data) {
String result = "";
try {
result = OBJECT_MAPPER.writeValueAsString(data);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return result;
}
呼び出し方
private JsonUtils sut;
public void testSerializeJson() {
Map<String, String> input = new HashMap<>();
input.put("testKey", "testValue");
String result = sut.serializeJson(input);
System.out.println(result);
}
実行結果
{"testKey":"testValue"}
デシリアライズ(Json文字列→data)
/** Jacksonのオブジェクトマッパー */
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* Jsonのデシリアライズ
*
* @param data
* @return
*/
public static <T> T deserializeJson(String json, Class<T> type) {
T result;
try {
result = type.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e);
}
try {
result = OBJECT_MAPPER.readValue(json, type);
} catch (JsonProcessingException e1) {
e1.printStackTrace();
throw new RuntimeException(e1);
}
return result;
}
呼び出し方
public void testDeserializeJson() {
String input = "{\"testKey\":\"testValue\"}";
Map<String, String> result = sut.deserializeJson(input, HashMap.class);
System.out.println(result);
}
実行結果
{testKey=testValue}