「Gradle」@JsonIgnorePropertiesでJava複数のフィールドをjson文字列に変換しない
構文
ObjectMapper mapper = new ObjectMapper();
String json文字列= mapper.writeValueAsString(javaオブジェクト名);
使用例
1.build.gradle(gradleプロジェクトの設定ファイル)
dependencies {
// jackson-databindの導入
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.13.0'
}
2.クラスの定義
書式
@JsonIgnoreProperties({ フィールド1, フィールド2 })
使用例
package com.arkgame.course;
// 複数のフィールドが変換の対象外
@JsonIgnoreProperties({ "age", "addr" })
public class User {
public int age;
public String username;
public String addr;
}
3.実行クラス(main)
package com.arkgame.course;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class ObjJsonDemo {
public static void main(String[] args) throws JsonProcessingException {
// Userのインスタンスの生成
User user = new User();
// クラスのメンバーの値を設定
user.username = "山田 太郎";
user.age = 32;
user.addr = "東京品川区";
// ObjectMapper変数の宣言
ObjectMapper mapper = new ObjectMapper();
// JSON文字列をインデントする
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// JavaオブジェクトをJSON文字列に変換
String res = mapper.writeValueAsString(user);
System.out.println("JSON文字列をインデントして表示:\n" + res);
}
}
実行結果
JSON文字列をインデントして表示:
{
“age" : 32,
“username" : “山田 太郎"
}