摘要:系列文章地址文檔可以輕松的將對象轉(zhuǎn)換成對象和文檔,同樣也可以將轉(zhuǎn)換成對象。在項目中如果要引入,可以直接利用或者引入注意,項目已經(jīng)自動依賴了與,不需要額外重復(fù)引入。
JacksonGithub 系列文章地址
jackson-databind文檔
Jackson可以輕松的將Java對象轉(zhuǎn)換成json對象和xml文檔,同樣也可以將json、xml轉(zhuǎn)換成Java對象。在項目中如果要引入Jackson,可以直接利用Maven或者Gradle引入:
... 2.7.0 ...... ... com.fasterxml.jackson.core jackson-databind ${jackson.version}
注意,databind項目已經(jīng)自動依賴了jackson-core與jackson-annotation,不需要額外重復(fù)引入。
Convert Java to JSON首先聲明有一個簡單的POJO:
// Note: can use getters/setters as well; here we just use public fields directly: public class MyValue { public String name; public int age; // NOTE: if using getters/setters, can keep fields `protected` or `private` }
然后創(chuàng)建一個ObjectMapper實例用于進(jìn)行轉(zhuǎn)化:
ObjectMapper mapper = new ObjectMapper(); // create once, reuse
MyValue value = mapper.readValue(new File("data.json"), MyValue.class); // or: value = mapper.readValue(new URL("http://some.com/api/entry.json"), MyValue.class); // or: value = mapper.readValue("{"name":"Bob", "age":13}", MyValue.class);
我們可以參考一個實例,將某個Staff的信息轉(zhuǎn)化為JSON然后寫入到文件中,首先來定義實體類:
package com.mkyong.json; import java.math.BigDecimal; import java.util.List; public class Staff { private String name; private int age; private String position; private BigDecimal salary; private Listskills; //getters and setters
然后具體的將Java實體類轉(zhuǎn)化為JSON的語句為:
package com.mkyong.json; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Jackson2Example { public static void main(String[] args) { Jackson2Example obj = new Jackson2Example(); obj.run(); } private void run() { ObjectMapper mapper = new ObjectMapper(); Staff staff = createDummyObject(); try { // Convert object to JSON string and save into a file directly mapper.writeValue(new File("D:staff.json"), staff); // Convert object to JSON string String jsonInString = mapper.writeValueAsString(staff); System.out.println(jsonInString); // Convert object to JSON string and pretty print jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff); System.out.println(jsonInString); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private Staff createDummyObject() { Staff staff = new Staff(); staff.setName("mkyong"); staff.setAge(33); staff.setPosition("Developer"); staff.setSalary(new BigDecimal("7500")); Listskills = new ArrayList<>(); skills.add("java"); skills.add("python"); staff.setSkills(skills); return staff; } }
最終的輸出為:
//new json file is created in D:staff.json" {"name":"mkyong","age":33,"position":"Developer","salary":7500,"skills":["java","python"]} { "name" : "mkyong", "age" : 33, "position" : "Developer", "salary" : 7500, "skills" : [ "java", "python" ] }Properties:屬性處理 Rename:屬性重命名
public class Name { @JsonProperty("firstName") public String _first_name; }
在將Name實體類轉(zhuǎn)化為JSON的時候,就會變成:
{ "firstName" : "Bob" }Ignore:屬性忽略
public class Value { public int value; @JsonIgnore public int internalValue; }
最終生成的JSON是如下格式:
{ "value" : 42 }
也可以在類的頭部統(tǒng)一聲明:
@JsonIgnoreProperties({ "extra", "uselessValue" }) public class Value { public int value; }
那么如下的JSON字符串也是可以被轉(zhuǎn)化為該實體類的:
{ "value" : 42, "extra" : "fluffy", "uselessValue" : -13 }
對于意外地未知屬性,也可以統(tǒng)一忽略:
@JsonIgnoreProperties(ignoreUnknown=true) public class PojoWithAny { public int value; }@JsonView:動態(tài)控制展示的成員變量
首先定義一個簡單的View控制類:
package com.mkyong.json; public class Views { public static class Normal{}; public static class Manager extends Normal{}; }
在下面的代碼實現(xiàn)中,如果是選擇了Normal View,那么salary屬性將會被隱藏,而在Manager View狀態(tài)下,任何屬性都會被展示。
package com.mkyong.json; import java.math.BigDecimal; import java.util.List; import com.fasterxml.jackson.annotation.JsonView; public class Staff { @JsonView(Views.Normal.class) private String name; @JsonView(Views.Normal.class) private int age; @JsonView(Views.Normal.class) private String position; @JsonView(Views.Manager.class) private BigDecimal salary; @JsonView(Views.Normal.class) private Listskills;
在進(jìn)行Object轉(zhuǎn)化為JSON的過程中,進(jìn)行視圖控制:
package com.mkyong.json; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Jackson2Example { public static void main(String[] args) { Jackson2Example obj = new Jackson2Example(); obj.run(); } private void run() { ObjectMapper mapper = new ObjectMapper(); Staff staff = createDummyObject(); try { // Salary will be hidden System.out.println("Normal View"); String normalView = mapper.writerWithView(Views.Normal.class).writeValueAsString(staff); System.out.println(normalView); String jsonInString = "{"name":"mkyong","age":33,"position":"Developer","salary":7500,"skills":["java","python"]}"; Staff normalStaff = mapper.readerWithView(Views.Normal.class).forType(Staff.class).readValue(jsonInString); System.out.println(normalStaff); // Display everything System.out.println(" Manager View"); String managerView = mapper.writerWithView(Views.Manager.class).writeValueAsString(staff); System.out.println(managerView); Staff managerStaff = mapper.readerWithView(Views.Manager.class).forType(Staff.class).readValue(jsonInString); System.out.println(managerStaff); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private Staff createDummyObject() { Staff staff = new Staff(); staff.setName("mkyong"); staff.setAge(33); staff.setPosition("Developer"); staff.setSalary(new BigDecimal("7500")); Listskills = new ArrayList<>(); skills.add("java"); skills.add("python"); staff.setSkills(skills); return staff; } }
最終輸出的結(jié)果為:
Normal View {"name":"mkyong","age":33,"position":"Developer","skills":["java","python"]} Staff [name=mkyong, age=33, position=Developer, salary=null, skills=[java, python]] Manager View {"name":"mkyong","age":33,"position":"Developer","salary":7500,"skills":["java","python"]} Staff [name=mkyong, age=33, position=Developer, salary=7500, skills=[java, python]]Convert JSON to Java
將JSON轉(zhuǎn)化為Java的實體類同樣需要用到ObjectMapper對象:
mapper.writeValue(new File("result.json"), myResultObject); // or: byte[] jsonBytes = mapper.writeValueAsBytes(myResultObject); // or: String jsonString = mapper.writeValueAsString(myResultObject);
而如果我們要將JSON轉(zhuǎn)化為Java中的List或者M(jìn)ap的話,可以采用如下方式:
//將某個JSON轉(zhuǎn)化為List String json = "[{"name":"mkyong"}, {"name":"laplap"}]"; Listlist = mapper.readValue(json, new TypeReference >(){}); //將某個JSON轉(zhuǎn)化為Map String json = "{"name":"mkyong", "age":33}"; Map
map = mapper.readValue(json, new TypeReference
還是來看一個實例,:
package com.mkyong.json; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Jackson2Example { public static void main(String[] args) { Jackson2Example obj = new Jackson2Example(); obj.run(); } private void run() { ObjectMapper mapper = new ObjectMapper(); try { // Convert JSON string from file to Object Staff staff = mapper.readValue(new File("D:staff.json"), Staff.class); System.out.println(staff); // Convert JSON string to Object String jsonInString = "{"name":"mkyong","salary":7500,"skills":["java","python"]}"; Staff staff1 = mapper.readValue(jsonInString, Staff.class); System.out.println(staff1); //Pretty print String prettyStaff1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff1); System.out.println(prettyStaff1); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
最終的輸出為:
Staff [name=mkyong, age=33, position=Developer, salary=7500, skills=[java, python]] Staff [name=mkyong, age=0, position=null, salary=7500, skills=[java, python]] { "name" : "mkyong", "age" : 0, "position" : null, "salary" : 7500, "skills" : [ "java", "python" ] }Tree Model:抽象的JSON數(shù)據(jù)類型,類似于FastJSON中的JSONObject
// can be read as generic JsonNode, if it can be Object or Array; or, // if known to be Object, as ObjectNode, if array, ArrayNode etc: ObjectNode root = mapper.readTree("stuff.json"); String name = root.get("name").asText(); int age = root.get("age").asInt(); // can modify as well: this adds child Object as property "other", set property "type" root.with("other").put("type", "student"); String json = mapper.writeValueAsString(root); // with above, we end up with something like as "json" String: // { // "name" : "Bob", "age" : 13, // "other" : { // "type" : "student" // } // }Constructor:自定義構(gòu)造器
默認(rèn)情況下,Jackson使用默認(rèn)的構(gòu)造器創(chuàng)建新的對象,不過你也可以使用@JsonCreator與@JsonProperty注解來自定義對象創(chuàng)建函數(shù)與值的綁定。
public class CtorPOJO { private final int _x, _y; @JsonCreator public CtorPOJO(@JsonProperty("x") int x, @JsonProperty("y") int y) { _x = x; _y = y; } }
public class DelegatingPOJO { private final int _x, _y; @JsonCreator public DelegatingPOJO(Mapdelegate) { _x = (Integer) delegate.get("x"); _y = (Integer) delegate.get("y"); } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/64807.html
摘要:開發(fā)應(yīng)用程序非常適合應(yīng)用程序開發(fā),通過使用嵌入式或,你可以創(chuàng)建一個自包含的服務(wù)器。如果你還沒有開發(fā)過一個應(yīng)用程序,你可以按照入門部分中的示例進(jìn)行操作。自動配置為大多數(shù)應(yīng)用程序提供了良好的自動配置。 27. 開發(fā)Web應(yīng)用程序 Spring Boot非常適合web應(yīng)用程序開發(fā),通過使用嵌入式Tomcat、Jetty、Undertow或Netty,你可以創(chuàng)建一個自包含的HTTP服務(wù)器。大多...
摘要:在本文中,我們將展示如何根據(jù)中定義的用戶角色過濾序列化輸出。請注意,此方法要求我們在處理具有多個角色的用戶時要小心。 在本文中,我們將展示如何根據(jù)Spring Security中定義的用戶角色過濾JSON序列化輸出。 為什么我們需要過濾? 讓我們考慮一個簡單但常見的用例,我們有一個Web應(yīng)用程序,為不同角色的用戶提供服務(wù)。例如,這些角色為User和Admin。 首先,讓我們定義一個要...
摘要:最佳解析最佳解析最佳解析是一個依賴注入框架,由谷歌開發(fā),最早的版本由公司開發(fā)。在對的介紹中指出,即,這里的即數(shù)據(jù)結(jié)構(gòu)中的有向無環(huán)圖。也就是說,是一個基于有向無環(huán)圖結(jié)構(gòu)的依賴注入庫,因此的使用過程中不能出現(xiàn)循環(huán)依賴。 在開發(fā)過程中使用過很多優(yōu)秀框架,比如網(wǎng)絡(luò)的okhttp,圖片的Fresco,注入的Gagger2等,都是非常優(yōu)秀的框架。 所以今天在此介紹下至今本人知道的一些比較流行主流且...
閱讀 2178·2023-04-25 19:06
閱讀 1375·2021-11-17 09:33
閱讀 1767·2019-08-30 15:53
閱讀 2582·2019-08-30 14:20
閱讀 3541·2019-08-29 12:58
閱讀 3534·2019-08-26 13:27
閱讀 501·2019-08-26 12:23
閱讀 485·2019-08-26 12:22