Serializācija anotācijas tiek izmantotas, serializējot Java objektus Json virknē. Džeksona bibliotēka nodrošina vairākas serializācijas anotācijas, piemēram, @JsonSerialize, @JacksonGetter, @JsonAnyGetter utt.
Izpratīsim katru no tiem pa vienam ar piemēru.
@JsonAnyGetter
@JsonAnyGetter ir viena no svarīgākajām anotācijām, ko izmanto JSON papildu rekvizītu serializēšanai tāpat kā citi rekvizīti tiek serializēti. Anotācija ļauj izmantot gettera metodi, lai atgrieztu karti, kuru pēc tam izmantojām serializēšanai. Serializācijai tiek izmantota JsonAnyGetter anotācija, kas nozīmē, ka tā ietilpst kategorijā Serializācijas anotācija .
Ņemsim divus piemērus, lai saprastu @JsonAnyGetter anotācija. Pirmajā piemērā mēs pārveidosim Java objektu par JSON, neizmantojot anotāciju. Otrajā piemērā mēs to darām, izmantojot anotāciju, lai izprastu @JsonAnyGetter anotācijas izmantošanu.
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); } }
Izvade:
kaut kas priekš bfs
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); } }
Izvade:
Paskaidrojums:
Izvade nāk ar a fakultāteDati galvene pirmajā piemērā, jo mēs neizmantojam @JsonAnyGetter anotāciju. Otrajā piemērā izvadei ir tikai Id, Name un Email vērtības. Izvadē nav facultyData galvenes, jo mēs izmantojam @JsonAnyGetter anotācija tur.
@JsonGetter
@JsonGetter ir vēl viena vissvarīgākā anotācija, ko izmanto JSON papildu rekvizītu serializēšanai. Tas ir līdzīgs @JsonProperty anotācijai, kas ļauj atzīmēt konkrētu metodi kā ieguves metodi. @JsonGetter anotācija tiek izmantota arī serializēšanai, tāpēc tā tiek izmantota Serializācijas anotācija .
avl koki
Ņemsim divus piemērus, lai saprastu @JsonGetter anotācija. Pirmajā piemērā mēs pārveidosim Java objektu par JSON, neizmantojot anotāciju. Otrajā piemērā mēs to darām, izmantojot anotāciju, lai izprastu @JsonGetter anotācijas izmantošanu.
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; } }
Izvade:
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; } }
Izvade:
Paskaidrojums
Pirmajā piemērā katra mainīgā nosaukums sākas ar fakultātes prefiksu, jo mēs neizmantojam @JsonGetter anotāciju. Otrajā piemērā mainīgo nosaukumi sākas bez prefiksa(fakultātes) vērtībām.
@JsonPropertyOrder
@JsonPropertyOrder ir vēl viena svarīga Džeksona anotācija. To izmanto, lai saglabātu noteiktu secību, serializējot JSON objektu. To izmanto arī serializēšanai, tāpēc tas arī tiek izmantots Serializācijas anotācija .
Ņemsim divus piemērus, lai saprastu @JsonPropertyOrder anotācija. Abu kodu loģika un funkcionalitāte ir līdzīga. Vienīgā atšķirība starp abiem ir tā, ka pirmajā kodā mēs to neizmantojam @JsonPropertyOrder, un otrajā mēs to izmantojam.
JsonPropertyOrderExample1.java
mainiet nosaukumu direktorija Linux
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 + ']'; } }
Izvade:
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 + ']'; } }
Izvade:
Paskaidrojums
Pirmajā piemērā izvade tiek piegādāta ar noklusējuma lauku secību, jo mēs to neizmantojam @JsonPropertyOrder . Otrajā piemērā izvade tiek iegūta ar to lauku secību, kurā mēs definējam @JsonPropertyOrder . Tātad, JsonProprtyOrder anotācija tiek izmantota, lai iegūtu rezultāta lauku norādītajā secībā.
@JsonRawValue
@JsonRawValue ir vēl viena svarīga Džeksona anotācija, ko izmanto objekta serializācijā. To izmanto teksta serializēšanai bez aizbēgšanas vai bez dekorācijas. Tas arī ienāk Serializācijas anotācija s.
Ņemsim piemērus, lai saprastu to izmantošanu @JsonRawValue anotācija, kurā mēs rakstām kodu ar un bez @JsonRawValue anotācija.
kārtot masīvu sarakstu
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 + ']'; } }
Izvade:
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 + ']'; } }
Izvade:
Paskaidrojums
Pirmajā piemērā lauka json vērtība ir saistīta ar apdari, jo mēs to neizmantojam @JsonRawValue anotācija. Savukārt otrajā piemērā lauka json vērtība tiek parādīta bez aizplūšanas vai dekorēšanas, jo mēs izmantojam @JsonRawValue anotācija. Tātad vērtības tiek norādītas bez slīpsvītras (/).
@JsonValue
@JsonValue ir viena no visbiežāk izmantotajām un svarīgākajām anotācijām, kas tiek izmantota viena objekta serializēšanai, izmantojot tā vienu metodi.
Ņemsim piemēru, lai saprastu, kā anotācija tiek izmantota objekta serializēšanai:
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 + '}'; } }
Izvade:
@JsonRootName
@JsonRootName anotācija ir viena no vissvarīgākajām anotācijām, kas tiek izmantota, lai norādītu POJO nosaukumu, kas jāveido sērijveidā. Vienkāršiem vārdiem sakot, to izmanto objekta iesaiņošanai serializēšanai ar augstākā līmeņa elementu. Tas ietilpst arī kategorijā Serializācijas anotācija .
java virknes indekss
Mēs nododam nosaukumu kā parametru anotācijai. Mēs arī izmantojam 'WRAP_ROOT_VALUE' , t.i., SerializationFeature enum līdzeklis. Mēs to iespējojam maršruta vērtības iesaiņošanai vienā rekvizīta JSON objektā, kur atslēga ir maršruta nosaukums.
Ņemsim piemēru @JsonRootName lai saprastu, kā tas darbojas:
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 + ']'; } }
Izvade:
@JsonSerialize
@JsonSerialize ir viena no visbiežāk izmantotajām anotācijām Java objekta serializēšanas laikā. To izmanto, lai definētu pielāgotu serializētāju Json objekta kārtošanai.
Ņemsim piemēru, lai saprastu, kā tas palīdz objekta serializācijā.
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)); } }
Izvade: