摘要:系列文章地址文档可以轻松的将对象转换成对象和文档,同样也可以将转换成对象。在项目中如果要引入,可以直接利用或者引入注意,项目已经自动依赖了与,不需要额外重复引入。
JacksonGithub 系列文章地址
jackson-databind文档
Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。在项目中如果要引入Jackson,可以直接利用Maven或者Gradle引入:
... 2.7.0 ...... ... com.fasterxml.jackson.core jackson-databind ${jackson.version}
注意,databind项目已经自动依赖了jackson-core与jackson-annotation,不需要额外重复引入。
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` }
然后创建一个ObjectMapper实例用于进行转化:
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的信息转化为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实体类转化为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实体类转化为JSON的时候,就会变成:
{ "firstName" : "Bob" }Ignore:属性忽略
public class Value { public int value; @JsonIgnore public int internalValue; }
最终生成的JSON是如下格式:
{ "value" : 42 }
也可以在类的头部统一声明:
@JsonIgnoreProperties({ "extra", "uselessValue" }) public class Value { public int value; }
那么如下的JSON字符串也是可以被转化为该实体类的:
{ "value" : 42, "extra" : "fluffy", "uselessValue" : -13 }
对于意外地未知属性,也可以统一忽略:
@JsonIgnoreProperties(ignoreUnknown=true) public class PojoWithAny { public int value; }@JsonView:动态控制展示的成员变量
首先定义一个简单的View控制类:
package com.mkyong.json; public class Views { public static class Normal{}; public static class Manager extends Normal{}; }
在下面的代码实现中,如果是选择了Normal View,那么salary属性将会被隐藏,而在Manager View状态下,任何属性都会被展示。
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;
在进行Object转化为JSON的过程中,进行视图控制:
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; } }
最终输出的结果为:
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转化为Java的实体类同样需要用到ObjectMapper对象:
mapper.writeValue(new File("result.json"), myResultObject); // or: byte[] jsonBytes = mapper.writeValueAsBytes(myResultObject); // or: String jsonString = mapper.writeValueAsString(myResultObject);
而如果我们要将JSON转化为Java中的List或者Map的话,可以采用如下方式:
//将某个JSON转化为List String json = "[{"name":"mkyong"}, {"name":"laplap"}]"; Listlist = mapper.readValue(json, new TypeReference >(){}); //将某个JSON转化为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数据类型,类似于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:自定义构造器
默认情况下,Jackson使用默认的构造器创建新的对象,不过你也可以使用@JsonCreator与@JsonProperty注解来自定义对象创建函数与值的绑定。
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"); } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/64807.html
摘要:开发应用程序非常适合应用程序开发,通过使用嵌入式或,你可以创建一个自包含的服务器。如果你还没有开发过一个应用程序,你可以按照入门部分中的示例进行操作。自动配置为大多数应用程序提供了良好的自动配置。 27. 开发Web应用程序 Spring Boot非常适合web应用程序开发,通过使用嵌入式Tomcat、Jetty、Undertow或Netty,你可以创建一个自包含的HTTP服务器。大多...
摘要:在本文中,我们将展示如何根据中定义的用户角色过滤序列化输出。请注意,此方法要求我们在处理具有多个角色的用户时要小心。 在本文中,我们将展示如何根据Spring Security中定义的用户角色过滤JSON序列化输出。 为什么我们需要过滤? 让我们考虑一个简单但常见的用例,我们有一个Web应用程序,为不同角色的用户提供服务。例如,这些角色为User和Admin。 首先,让我们定义一个要...
摘要:最佳解析最佳解析最佳解析是一个依赖注入框架,由谷歌开发,最早的版本由公司开发。在对的介绍中指出,即,这里的即数据结构中的有向无环图。也就是说,是一个基于有向无环图结构的依赖注入库,因此的使用过程中不能出现循环依赖。 在开发过程中使用过很多优秀框架,比如网络的okhttp,图片的Fresco,注入的Gagger2等,都是非常优秀的框架。 所以今天在此介绍下至今本人知道的一些比较流行主流且...
阅读 2181·2023-04-25 19:06
阅读 1377·2021-11-17 09:33
阅读 1768·2019-08-30 15:53
阅读 2583·2019-08-30 14:20
阅读 3543·2019-08-29 12:58
阅读 3535·2019-08-26 13:27
阅读 503·2019-08-26 12:23
阅读 486·2019-08-26 12:22