logo

Opombe serializacije v Jacksonu

Serializacija opombe se uporabljajo, ko objekte Java serializiramo v niz Json. Jacksonova knjižnica ponuja več opomb za serializacijo, kot je npr @JsonSerialize, @JacksonGetter, @JsonAnyGetter itd.

optični bralnik naslednji
Opombe serializacije v Jacksonu

Razumejmo vsakega od njih enega za drugim s primerom.

@JsonAnyGetter

@JsonAnyGetter je ena najpomembnejših opomb, ki se uporablja za serializacijo dodatnih lastnosti JSON na enak način, kot so serializirane druge lastnosti. Opomba omogoča metodi pridobivanja za vrnitev zemljevida, ki smo ga nato uporabili za serializacijo. Opomba JsonAnyGetter se uporablja za serializacijo, kar pomeni, da spada v kategorijo Opomba o serializaciji .

Za razumevanje vzemimo dva primera @JsonAnyGetter opomba. V prvem primeru bomo Java Object pretvorili v JSON brez uporabe pripisov. V drugem primeru to storimo z uporabo pripisov, da razumemo uporabo pripisov @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); } } 

Izhod:

Opombe serializacije v Jacksonu

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); } } 

Izhod:

Opombe serializacije v Jacksonu

Pojasnilo:

Izhod je opremljen z a facultyData glave v prvem primeru, ker ne uporabljamo pripisa @JsonAnyGetter. V drugem primeru so izhodni podatki samo z vrednostmi Id, Name in Email. V izhodu ni glave facultyData, ker uporabljamo @JsonAnyGetter opomba tam.

@JsonGetter

@JsonGetter je še ena najpomembnejša opomba, ki se uporablja za serializacijo dodatnih lastnosti JSON. Podobno je pripisu @JsonProperty, ki omogoča, da je določena metoda označena kot metoda pridobivanja. Opomba @JsonGetter se uporablja tudi za serializacijo, zato je vključena Opomba o serializaciji .

Za razumevanje vzemimo dva primera @JsonGetter opomba. V prvem primeru bomo Java Object pretvorili v JSON brez uporabe pripisov. V drugem primeru to storimo z uporabo pripisov, da razumemo uporabo pripisov @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; } } 

Izhod:

Opombe serializacije v Jacksonu

JsonGetterExample2.java

windows.open javascript
 //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; } } 

Izhod:

Opombe serializacije v Jacksonu

Razlaga

V prvem primeru se vsako ime spremenljivke začne s predpono fakultete, ker ne uporabljamo oznake @JsonGetter. Imena spremenljivk se v drugem primeru začnejo brez vrednosti predpone (faculty).

@JsonPropertyOrder

@JsonPropertyOrder je še ena pomembna opomba o Jacksonu. Uporablja se za ohranitev določenega vrstnega reda pri serializaciji objekta JSON. Uporablja se tudi za serializacijo, zato tudi pride Opomba o serializaciji .

Za razumevanje vzemimo dva primera @JsonPropertyOrder opomba. Logika in funkcionalnost obeh kod je podobna. Edina razlika med obema je, da v prvi kodi ne uporabljamo @JsonPropertyOrder, v drugem pa ga uporabimo.

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 + ']'; } } 

Izhod:

Opombe serializacije v Jacksonu

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 + ']'; } } 

Izhod:

Opombe serializacije v Jacksonu

Razlaga

kako prekličeš izbiro v gimp

V prvem primeru je izhod privzet s privzetim vrstnim redom polj, ker ne uporabljamo @JsonPropertyOrder . V drugem primeru izhod vsebuje vrstni red polj, v katerih definiramo @JsonPropertyOrder . Opomba JsonProprtyOrder se torej uporablja za pridobitev polja rezultata v podanem vrstnem redu.

@JsonRawValue

@JsonRawValue je še ena pomembna opomba Jacksona, ki se uporablja pri serializaciji predmeta. Uporablja se za serializacijo besedila brez uhajanja ali brez okraskov. Prav tako pride Opomba o serializaciji s.

Vzemimo primere za razumevanje uporabe @JsonRawValue anotacija, v katero zapišemo kodo z in brez @JsonRawValue opomba.

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 + ']'; } } 

Izhod:

Opombe serializacije v Jacksonu

JsonRawValueExample2.java

ipconfig v Ubuntuju
 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 + ']'; } } 

Izhod:

Opombe serializacije v Jacksonu

Razlaga

V prvem primeru je vrednost polja json opremljena z dekoracijo, ker je ne uporabljamo @JsonRawValue opomba. Medtem ko je v drugem primeru vrednost polja json brez ubežnikov ali okraskov, ker uporabljamo @JsonRawValue opomba. Torej so vrednosti brez poševnice (/).

@JsonValue

@JsonValue je ena najpogosteje uporabljenih in najpomembnejših opomb, ki se uporablja za serializacijo posameznega predmeta z uporabo njegove ene metode.

Vzemimo primer, da razumemo, kako se opomba uporablja za serializacijo predmeta:

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 + '}'; } } 

Izhod:

drugače če bash
Opombe serializacije v Jacksonu

@JsonRootName

@JsonRootName opomba je ena najpomembnejših opomb, ki se uporablja za označevanje imena POJO, ki ga je treba serializirati. Preprosto povedano, uporablja se za ovijanje predmeta za serializacijo z elementom najvišje ravni. Prav tako spada v kategorijo Opomba o serializaciji .

Ime posredujemo kot parameter pripisu. Uporabljamo tudi 'WRAP_ROOT_VALUE' , tj. funkcija enuma SerializationFeature. Omogočimo ga za ovijanje vrednosti poti znotraj posameznega objekta JSON lastnosti, kjer je ključ ime poti.

Vzemimo primer @JsonRootName da razumete, kako deluje:

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 + ']'; } } 

Izhod:

Opombe serializacije v Jacksonu

@JsonSerialize

@JsonSerialize je ena najpogosteje uporabljenih opomb pri serializaciji objekta Java. Uporablja se za definiranje serializatorja po meri za razvrščanje objekta Json.

Vzemimo primer, da razumemo, kako pomaga pri serializaciji predmeta.

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)); } } 

Izhod:

Opombe serializacije v Jacksonu