logo

Jackson でのシリアル化の注釈

連載 注釈は、Java オブジェクトを Json 文字列にシリアル化するときに使用されます。 Jackson ライブラリは、次のようないくつかのシリアル化アノテーションを提供します。 @JsonSerialize、@JacksonGetter、@JsonAnyGetter 、など。

Jackson でのシリアル化の注釈

例を挙げて、それぞれを 1 つずつ理解してみましょう。

@JsonAnyGetter

@JsonAnyGetter は、他のプロパティがシリアル化されるのと同じ方法で、JSON の追加プロパティをシリアル化するために使用される最も重要なアノテーションの 1 つです。アノテーションにより、ゲッター メソッドが Map を返し、それをシリアル化に使用できるようになります。 JsonAnyGetter アノテーションはシリアル化に使用されます。つまり、次のカテゴリに属します。 シリアル化の注釈

を理解するために 2 つの例を見てみましょう @JsonAnyGetter 注釈。最初の例では、アノテーションを使用せずに Java オブジェクトを JSON に変換します。 2 番目の例では、 @JsonAnyGetter アノテーションの使用を理解するために、アノテーションを使用してこれを実行します。

JsonAnyGetterExample1.java

 // import required classes and package import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import com.fasterxml.jackson.databind.ObjectMapper; // create class JsonAnyGetterExample1 public class JsonAnyGetterExample1 { // main() method start public static void main(String args[]){ // create instance of ObjectMapper class ObjectMapper mapper = new ObjectMapper(); // create Scanner class object Scanner sc= new Scanner(System.in); try{ Faculty faculty = new Faculty(); String facId, facname, facEmail; System.out.println('Enter Faculty Id:'); facId = sc.nextLine(); faculty.add('Id', facId); System.out.println('Enter Faculty Name'); facname = sc.nextLine(); faculty.add('Name', facname); System.out.println('Enter Faculty Email'); facEmail = sc.nextLine(); faculty.add('Email', facEmail); // convert Java type into Json string String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(faculty); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace(); } // close Scanner class object sc.close(); } } class Faculty { private Map facultyData; public Faculty(){ facultyData = new HashMap(); } public Map getFacultyData(){ return facultyData; } public void add(String key, String value){ facultyData.put(key, value); } } 

出力:

おっとコンセプト
Jackson でのシリアル化の注釈

JsonAnyGetterExample2.java

 // import required classes and package import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.databind.ObjectMapper; // create class JsonAnyGetterExample2 to understand use of @JsonAnyGetter public class JsonAnyGetterExample2 { // main() method start public static void main(String args[]){ // create instance of ObjectMapper class ObjectMapper mapper = new ObjectMapper(); // create Scanner class object Scanner sc= new Scanner(System.in); try{ Faculty faculty = new Faculty(); String facId, facname, facEmail; System.out.println('Enter Faculty Id:'); facId = sc.nextLine(); faculty.add('Id', facId); System.out.println('Enter Faculty Name'); facname = sc.nextLine(); faculty.add('Name', facname); System.out.println('Enter Faculty Email'); facEmail = sc.nextLine(); faculty.add('Email', facEmail); // convert Java type into Json string String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(faculty); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace(); } // close Scanner class object sc.close(); } } class Faculty { private Map facultyData; public Faculty(){ facultyData = new HashMap(); } @JsonAnyGetter public Map getFacultyData(){ return facultyData; } public void add(String key, String value){ facultyData.put(key, value); } } 

出力:

Jackson でのシリアル化の注釈

説明:

出力には、 教員データ 最初の例のヘッダーは、 @JsonAnyGetter アノテーションを使用していないためです。 2 番目の例では、出力には ID、名前、および電子メールの値のみが含まれます。を使用しているため、出力にはfacultyDataヘッダーはありません。 @JsonAnyGetter そこに注釈が付いています。

@JsonGetter

@JsonGetter これは、JSON の追加プロパティをシリアル化するために使用されるもう 1 つの最も重要なアノテーションです。これは、特定のメソッドをゲッター メソッドとしてマークできるようにする @JsonProperty アノテーションに似ています。 @JsonGetter アノテーションはシリアル化にも使用されるため、これが入っています シリアル化の注釈

を理解するために 2 つの例を見てみましょう @JsonGetter 注釈。最初の例では、アノテーションを使用せずに Java オブジェクトを JSON に変換します。 2 番目の例では、 @JsonGetter アノテーションの使用を理解するために、アノテーションを使用してこれを実行します。

JsonGetterExample1.java

 //import required classes and package import java.io.IOException; import java.util.Scanner; import com.fasterxml.jackson.databind.ObjectMapper; //create class JsonGetterExample1 public class JsonGetterExample1 { // main() method start public static void main(String args[]){ // create instance of ObjectMapper class ObjectMapper mapper = new ObjectMapper(); // create Scanner class object Scanner sc= new Scanner(System.in); try{ String facId, facName, facEmail; System.out.println('Enter Faculty Id:'); facId = sc.nextLine(); System.out.println('Enter Faculty Name'); facName = sc.nextLine(); System.out.println('Enter Faculty Email'); facEmail = sc.nextLine(); FacultyNew faculty = new FacultyNew(facId, facName, facEmail); // convert Java type into Json string String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(faculty); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace(); } // close Scanner class object sc.close(); } } class FacultyNew { private String facId; private String facName; private String facEmail; public FacultyNew(String id, String name, String email){ facId = id; facName = name; facEmail = email; } public String getId(){ return facId; } public String getName(){ return facName; } public String getEmail(){ return facEmail; } } 

出力:

Jackson でのシリアル化の注釈

JsonGetterExample2.java

 //import required classes and package import java.io.IOException; import java.util.Scanner; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.databind.ObjectMapper; //create class JsonGetterExample2 to understand the JsonGetter annotation public class JsonGetterExample2 { // main() method start public static void main(String args[]){ // create instance of ObjectMapper class ObjectMapper mapper = new ObjectMapper(); // create Scanner class object Scanner sc= new Scanner(System.in); try{ String facId, facName, facEmail; System.out.println('Enter Faculty Id:'); facId = sc.nextLine(); System.out.println('Enter Faculty Name'); facName = sc.nextLine(); System.out.println('Enter Faculty Email'); facEmail = sc.nextLine(); FacultyNew faculty = new FacultyNew(facId, facName, facEmail); // convert Java type into Json string String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(faculty); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace(); } // close Scanner class object sc.close(); } } class FacultyNew { private String id; private String name; private String email; public FacultyNew(String id, String name, String email){ this.id = id; this.name = name; this.email = email; } public String getFacultyId(){ return id; } @JsonGetter('name') public String getFacultyName(){ return name; } public String getFacultyEmail(){ return email; } } 

出力:

Jackson でのシリアル化の注釈

説明

最初の例では、@JsonGetter アノテーションを使用していないため、各変数名は学部の接頭辞で始まります。 2 番目の例では、変数名は prefix(faculty) 値なしで始まります。

@JsonPropertyOrder

@JsonPropertyOrder もジャクソンの重要な注釈です。これは、JSON オブジェクトをシリアル化するときに特定の順序を保持するために使用されます。連載にも使われているので、 シリアル化の注釈

を理解するために 2 つの例を見てみましょう @JsonPropertyOrder 注釈。両方のコードのロジックと機能は似ています。両方の唯一の違いは、最初のコードでは、 @JsonPropertyOrder、 2 番目ではそれを使用します。

JsonPropertyOrderExample1.java

 import java.io.IOException; import java.util.Scanner; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; // create JsonPropertyOrderExample1 class to convert Java Object into JSON public class JsonPropertyOrderExample1 { // main() method start public static void main(String args[]){ // create instance of the ObjectSerialization class ObjectMapper obj = new ObjectMapper(); Scanner sc1 = new Scanner(System.in); try { Product prod = new Product(); String prodId, prodName, price; System.out.println('Enter Product Id:'); prodId = sc1.nextLine(); prod.setProId(prodId); System.out.println('Enter Product Name'); prodName = sc1.nextLine(); prod.setProName(prodName); System.out.println('Enter Product Price:'); price = sc1.nextLine(); prod.setPrice(price); String jsonString = obj .writerWithDefaultPrettyPrinter() .writeValueAsString(prod); System.out.println(jsonString); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // close scanner class object sc1.close(); } } class Product { //Creating properties of Product class private String proId; private String name; private String price; //Getter and Setters public String getProId() { return proId; } public void setProId(String proId) { this.proId = proId; } public String getName() { return name; } public void setProName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } @Override public String toString() { // TODO Auto-generated method stub return ''Product [ProductId '+ proId + ', ProductName = ' + name + ', ProductPrice = ' + price + ']'; } } 

出力:

Jackson でのシリアル化の注釈

JsonPropertyOrderExample2.java

 import java.io.IOException; import java.util.Scanner; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; // create JsonPropertyOrderExample1 class to convert Java Object into JSON public class JsonPropertyOrderExample1 { // main() method start public static void main(String args[]){ // create instance of the ObjectSerialization class ObjectMapper obj = new ObjectMapper(); Scanner sc1 = new Scanner(System.in); try { Product prod = new Product(); String prodId, prodName, price; System.out.println('Enter Product Id:'); prodId = sc1.nextLine(); prod.setProId(prodId); System.out.println('Enter Product Name'); prodName = sc1.nextLine(); prod.setProName(prodName); System.out.println('Enter Product Price:'); price = sc1.nextLine(); prod.setPrice(price); String jsonString = obj .writerWithDefaultPrettyPrinter() .writeValueAsString(prod); System.out.println(jsonString); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // close scanner class object sc1.close(); } } @JsonPropertyOrder({'name', 'proId'}) class Product { //Creating properties of Product class private String proId; private String name; private String price; //Getter and Setters public String getProId() { return proId; } public void setProId(String proId) { this.proId = proId; } public String getName() { return name; } public void setProName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } @Override public String toString() { // TODO Auto-generated method stub return ''Product [ProductId '+ proId + ', ProductName = ' + name + ', ProductPrice = ' + price + ']'; } } 

出力:

Jackson でのシリアル化の注釈

説明

最初の例では、フィールドを使用しないため、出力はデフォルトのフィールド順序で表示されます。 @JsonPropertyOrder 。 2 番目の例では、出力は、で定義したフィールドの順序で提供されます。 @JsonPropertyOrder 。したがって、JsonProprtyOrder アノテーションを使用して、指定された順序で結果フィールドを取得します。

@JsonRawValue

@JsonRawValue は、オブジェクトをシリアル化する際に使用される Jackson のもう 1 つの重要なアノテーションです。これは、エスケープや装飾を行わずにテキストをシリアル化するために使用されます。それも入ってくる シリアル化の注釈 s.

の使用法を理解するために例を見てみましょう @JsonRawValue アノテーションを使用して、または使用せずにコードを記述します。 @JsonRawValue 注釈。

JsonRawValueExample1.java

 import java.io.IOException; import java.util.Scanner; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; // create JsonRawValueExample1 class to convert Java Object into JSON public class JsonRawValueExample1 { // main() method start public static void main(String args[]){ // create instance of the ObjectSerialization class ObjectMapper obj = new ObjectMapper(); Scanner sc1 = new Scanner(System.in); try { Product prod = new Product(); String prodId, prodName, price; System.out.println('Enter Product Id:'); prodId = sc1.nextLine(); prod.setProId(prodId); System.out.println('Enter Product Name'); prodName = sc1.nextLine(); prod.setProName(prodName); System.out.println('Enter Product Price:'); price = sc1.nextLine(); prod.setPrice(price); prod.setJson('{'attr':false}'); String jsonString = obj .writerWithDefaultPrettyPrinter() .writeValueAsString(prod); System.out.println(jsonString); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // close scanner class object sc1.close(); } } class Product { //Creating properties of Product class private String proId; private String name; private String price; private String json; //Getter and Setters public String getProId() { return proId; } public void setProId(String proId) { this.proId = proId; } public String getName() { return name; } public void setProName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getJson() { return json; } public void setJson(String json) { this.json = json; } @Override public String toString() { // TODO Auto-generated method stub return ''Product [ProductId '+ proId + ', ProductName = ' + name + ', ProductPrice = ' + price + ']'; } } 

出力:

Jackson でのシリアル化の注釈

JsonRawValueExample2.java

 import java.io.IOException; import java.util.Scanner; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.annotation.JsonRawValue; // create JsonRawValueExample2 class to convert Java Object into JSON public class JsonRawValueExample2 { // main() method start public static void main(String args[]){ // create instance of the ObjectSerialization class ObjectMapper obj = new ObjectMapper(); Scanner sc1 = new Scanner(System.in); try { Product prod = new Product(); String prodId, prodName, price; System.out.println('Enter Product Id:'); prodId = sc1.nextLine(); prod.setProId(prodId); System.out.println('Enter Product Name'); prodName = sc1.nextLine(); prod.setProName(prodName); System.out.println('Enter Product Price:'); price = sc1.nextLine(); prod.setPrice(price); prod.setJson('{'attr':false}'); String jsonString = obj .writerWithDefaultPrettyPrinter() .writeValueAsString(prod); System.out.println(jsonString); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // close scanner class object sc1.close(); } } class Product { //Creating properties of Product class private String proId; private String name; private String price; @JsonRawValue private String json; //Getter and Setters public String getProId() { return proId; } public void setProId(String proId) { this.proId = proId; } public String getName() { return name; } public void setProName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getJson() { return json; } public void setJson(String json) { this.json = json; } @Override public String toString() { // TODO Auto-generated method stub return ''Product [ProductId '+ proId + ', ProductName = ' + name + ', ProductPrice = ' + price + ']'; } } 

出力:

Jackson でのシリアル化の注釈

説明

最初の例では、json フィールドの値には装飾が付いています。 @JsonRawValue 注釈。一方、2 番目の例では、json フィールドの値はエスケープや装飾なしで取得されます。 @JsonRawValue 注釈。したがって、値にはスラッシュ (/) がありません。

@JsonValue

@JsonValue は、単一のメソッドを使用して単一のオブジェクトをシリアル化するために使用される、最も使用され、最も重要なアノテーションの 1 つです。

注釈を使用してオブジェクトをシリアル化する方法を理解するための例を見てみましょう。

JsonValueExample1.java

 import java.io.IOException; import java.util.Scanner; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.annotation.JsonValue; // create JsonValueExample class to serialize an object using its single method public class JsonValueExample { // main() method start public static void main(String args[]){ // create instance of the ObjectSerialization class ObjectMapper obj = new ObjectMapper(); Scanner sc1 = new Scanner(System.in); try { Product prod = new Product(); String prodId, prodName, price; System.out.println('Enter Product Id:'); prodId = sc1.nextLine(); prod.setProId(prodId); System.out.println('Enter Product Name'); prodName = sc1.nextLine(); prod.setProName(prodName); System.out.println('Enter Product Price:'); price = sc1.nextLine(); prod.setPrice(price); String jsonString = obj .writerWithDefaultPrettyPrinter() .writeValueAsString(prod); System.out.println(jsonString); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // close scanner class object sc1.close(); } } class Product { //Creating properties of Product class private String proId; private String name; private String price; //Getter and Setters public String getProId() { return proId; } public void setProId(String proId) { this.proId = proId; } public String getName() { return name; } public void setProName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } @JsonValue public String toString() { // TODO Auto-generated method stub return '{ ProductId = '+ proId + ', ProductName = ' + name + ', ProductPrice = ' + price + '}'; } } 

出力:

Jackson でのシリアル化の注釈

@JsonRootName

@JsonRootName 注釈は、シリアル化する必要がある POJO の名前を示すために使用される最も重要な注釈の 1 つです。簡単に言うと、トップレベルの要素でシリアル化するためにオブジェクトをラップするために使用されます。というカテゴリーにも入ります シリアル化の注釈

マイライブクリケット

名前をパラメータとしてアノテーションに渡します。また、 「WRAP_ROOT_VALUE」 、つまり、SerializationFeature 列挙型の機能です。キーがルート名である単一のプロパティ JSON オブジェクト内でルート値をラップするためにこれを有効にします。

例を挙げてみましょう @JsonRootName それがどのように機能するかを理解するには:

JsonRootNameExample.java

 import java.io.IOException; import java.util.Scanner; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.annotation.JsonRootName; // create JsonRootNameExample class to serialize an object public class JsonRootNameExample { // main() method start public static void main(String args[]){ // create instance of the ObjectSerialization class ObjectMapper obj = new ObjectMapper(); Scanner sc1 = new Scanner(System.in); try { Product prod = new Product(); String prodId, prodName, price; System.out.println('Enter Product Id:'); prodId = sc1.nextLine(); prod.setProId(prodId); System.out.println('Enter Product Name'); prodName = sc1.nextLine(); prod.setProName(prodName); System.out.println('Enter Product Price:'); price = sc1.nextLine(); prod.setPrice(price); String jsonString = obj. enable(SerializationFeature.WRAP_ROOT_VALUE) .writerWithDefaultPrettyPrinter() .writeValueAsString(prod); System.out.println(jsonString); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // close scanner class object sc1.close(); } } @JsonRootName(value = 'Details') class Product { //Creating properties of Product class private String proId; private String name; private String price; //Getter and Setters public String getProId() { return proId; } public void setProId(String proId) { this.proId = proId; } public String getName() { return name; } public void setProName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } @Override public String toString() { // TODO Auto-generated method stub return ''Product [ProductId '+ proId + ', ProductName = ' + name + ', ProductPrice = ' + price + ']'; } } 

出力:

Jackson でのシリアル化の注釈

@JsonSerialize

@JsonSerialize Java オブジェクトをシリアル化するときに最も使用されるアノテーションの 1 つです。これは、Json オブジェクトをマーシャリングするためのカスタム シリアライザーを定義するために使用されます。

オブジェクトのシリアル化にどのように役立つかを理解するために例を見てみましょう。

JsonSerializerExample.java

 import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.StdSerializer; // create class JsonSerializeExample to understand how we can use custom specific serializer public class JsonSerializeExample { //main method start public static void main(String args[]) throws ParseException { // create instance of the ObjectSerialization class ObjectMapper obj = new ObjectMapper(); // create instance of SimpleDateFormat class to format a date SimpleDateFormat sdf = new SimpleDateFormat('dd-MM-yyyy'); Scanner sc1 = new Scanner(System.in); try { Product prod = new Product(); String prodId, prodName, price; Date exp; System.out.println('Enter Product Id:'); prodId = sc1.nextLine(); prod.setProId(prodId); System.out.println('Enter Product Name'); prodName = sc1.nextLine(); prod.setProName(prodName); System.out.println('Enter Product Price:'); price = sc1.nextLine(); prod.setPrice(price); System.out.println('Enter expiry date of product in dd-MM-yyyy format:'); exp = sdf.parse(sc1.nextLine()); prod.setDate(exp); String jsonString = obj .writerWithDefaultPrettyPrinter() .writeValueAsString(prod); System.out.println(jsonString); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } // create class Product class Product { //Creating properties of Product class private String proId; private String name; private String price; @JsonSerialize(using = DateSerializer.class) private Date expire; //Getter and Setters public String getProId() { return proId; } public void setProId(String proId) { this.proId = proId; } public String getName() { return name; } public void setProName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Date getDate() { return expire; } public void setDate(Date expire) { this.expire = expire; } } // create custom serializer by extending StdSerializer class DateSerializer extends StdSerializer { // declare and initialize serialVersionUID private static final long serialVersionUID = 1L; private static SimpleDateFormat sdf = new SimpleDateFormat('dd-MM-yyyy'); // default and parameterized constructor public DateSerializer() { this(null); } public DateSerializer(Class t) { super(t); } // override serialize method @Override public void serialize(Date d1, JsonGenerator jsonGen, SerializerProvider serializer) throws IOException { jsonGen.writeString(sdf.format(d1)); } } 

出力:

Jackson でのシリアル化の注釈