博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JSON解析-Jackson
阅读量:5757 次
发布时间:2019-06-18

本文共 10450 字,大约阅读时间需要 34 分钟。

JSON解析-Jackson

1.Jackson简介

参考链接:

简介:Jackson是一个简洁的方式去解析JSON开源包。Jackson可以解析JSON从String,Stream,或者file的方式去创建Java对象。Jackson不仅仅可以解析JSON到Java对象,也可以将Java对象解析为JSON字符串。原理:Java反射机制实现JSON和Java对象间数据自动转换。

2.Jackson下载安装:maven依赖方式添加

com.fasterxml.jackson.core
jackson-core
2.9.6
com.fasterxml.jackson.core
jackson-annotations
2.9.6
com.fasterxml.jackson.core
jackson-databind
2.9.6

3.Jackson ObjectMapper Jackson对象映射

从JSON字符串转换为Java对象

ObjectMapper objectMapper = new ObjectMapper();String carJson ="{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";Car car = objectMapper.readValue(carJson, Car.class);

从JSON Reader转换为Java对象

ObjectMapper objectMapper = new ObjectMapper();String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 4 }";Reader reader = new StringReader(carJson);Car car = objectMapper.readValue(reader, Car.class);

从File 文件中转换为Java对象

ObjectMapper objectMapper = new ObjectMapper();File file = new File("data/car.json");Car car = objectMapper.readValue(file, Car.class);

从URL(网络或本地资源) 资源转换为Java对象

ObjectMapper objectMapper = new ObjectMapper();URL url = new URL("file:data/car.json");Car car = objectMapper.readValue(url, Car.class);

从InputStream 输入流中转换为Java对象

ObjectMapper objectMapper = new ObjectMapper();InputStream input = new FileInputStream("data/car.json");Car car = objectMapper.readValue(input, Car.class);

从Byte Array 中转换为Java对象

ObjectMapper objectMapper = new ObjectMapper();String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";byte[] bytes = carJson.getBytes("UTF-8");Car car = objectMapper.readValue(bytes, Car.class);

从JSON字符数组中转换为Java对象数组(Array)

String jsonArray = "[{\"brand\":\"ford\"}, {\"brand\":\"Fiat\"}]";ObjectMapper objectMapper = new ObjectMapper();Car[] cars2 = objectMapper.readValue(jsonArray, Car[].class);

从JSON字符数组中转换为Java对象列表(List)

String jsonArray = "[{\"brand\":\"ford\"}, {\"brand\":\"Fiat\"}]";ObjectMapper objectMapper = new ObjectMapper();List
cars1 = objectMapper.readValue(jsonArray, new TypeReference
>(){});

从JSON字符串中转换为Java的Map存储

String jsonObject = "{\"brand\":\"ford\", \"doors\":5}";ObjectMapper objectMapper = new ObjectMapper();Map
jsonMap = objectMapper.readValue(jsonObject, new TypeReference
>(){});

忽略解析JSON字符串中Java对象中没有的字段设置

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

原始类型的空JSON值失败

int 值为null问题。

自定义反序列化器

1.应用String json = "{ \"brand\" : \"Ford\", \"doors\" : 6 }";SimpleModule module =new SimpleModule("CarDeserializer", new Version(3, 1, 8, null, null, null));module.addDeserializer(Car.class, new CarDeserializer(Car.class));ObjectMapper mapper = new ObjectMapper();mapper.registerModule(module);Car car = mapper.readValue(json, Car.class);2.定义import com.fasterxml.jackson.core.JsonParser;import com.fasterxml.jackson.core.JsonToken;import com.fasterxml.jackson.databind.DeserializationContext;import com.fasterxml.jackson.databind.deser.std.StdDeserializer;import java.io.IOException;public class CarDeserializer extends StdDeserializer
{ public CarDeserializer(Class
vc) { super(vc); } @Override public Car deserialize(JsonParser parser, DeserializationContext deserializer) throws IOException { Car car = new Car(); while(!parser.isClosed()){ JsonToken jsonToken = parser.nextToken(); if(JsonToken.FIELD_NAME.equals(jsonToken)){ String fieldName = parser.getCurrentName(); System.out.println(fieldName); jsonToken = parser.nextToken(); if("brand".equals(fieldName)){ car.setBrand(parser.getValueAsString()); } else if ("doors".equals(fieldName)){ car.setDoors(parser.getValueAsInt()); } } } return car; }}

从Java对象输出JSON

可以将Java对象输出到,JSON字符串,Byte数组,File外部文件中,OutPutStream输出流中ObjectMapper objectMapper = new ObjectMapper();Car car = new Car();car.brand = "BMW";car.doors = 4;objectMapper.writeValue(    new FileOutputStream("data/output-2.json"), car);String json = objectMapper.writeValueAsString(car);System.out.println(json);String json = objectMapper.writeValueAsBytes(car);

自定义序列化器

1.应用CarSerializer carSerializer = new CarSerializer(Car.class);ObjectMapper objectMapper = new ObjectMapper();SimpleModule module =        new SimpleModule("CarSerializer", new Version(2, 1, 3, null, null, null));module.addSerializer(Car.class, carSerializer);objectMapper.registerModule(module);Car car = new Car();car.setBrand("Mercedes");car.setDoors(5);String carJson = objectMapper.writeValueAsString(car);2.定义import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.databind.SerializerProvider;import com.fasterxml.jackson.databind.ser.std.StdSerializer;import java.io.IOException;public class CarSerializer extends StdSerializer
{ protected CarSerializer(Class
t) { super(t); } public void serialize(Car car, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("producer", car.getBrand()); jsonGenerator.writeNumberField("doorCount", car.getDoors()); jsonGenerator.writeEndObject(); }}

Jackson Date 日期格式化

1.默认Jackson 日期是以1970为开始的int类型的时间值。2.可以通过SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");objectMapper2.setDateFormat(dateFormat);设置具体Date日期的格式。

Jackson JSON的树模型

1.读取JSON作为Jackson JSON树形式String carJson =        "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";ObjectMapper objectMapper = new ObjectMapper();try {    JsonNode jsonNode = objectMapper.readValue(carJson, JsonNode.class);} catch (IOException e) {    e.printStackTrace();}String carJson =        "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";ObjectMapper objectMapper = new ObjectMapper();try {    JsonNode jsonNode = objectMapper.readTree(carJson);} catch (IOException e) {    e.printStackTrace();}2.完整实例String carJson =        "{ \"brand\" : \"Mercedes\", \"doors\" : 5," +        "  \"owners\" : [\"John\", \"Jack\", \"Jill\"]," +        "  \"nestedObject\" : { \"field\" : \"value\" } }";ObjectMapper objectMapper = new ObjectMapper();try {    JsonNode jsonNode = objectMapper.readValue(carJson, JsonNode.class);    JsonNode brandNode = jsonNode.get("brand");    String brand = brandNode.asText();    System.out.println("brand = " + brand);    JsonNode doorsNode = jsonNode.get("doors");    int doors = doorsNode.asInt();    System.out.println("doors = " + doors);    JsonNode array = jsonNode.get("owners");    JsonNode jsonNode = array.get(0);    String john = jsonNode.asText();    System.out.println("john  = " + john);    JsonNode child = jsonNode.get("nestedObject");    JsonNode childField = child.get("field");    String field = childField.asText();    System.out.println("field = " + field);} catch (IOException e) {    e.printStackTrace();}

Jackson 还可以读取COBR,MessagePack,YAML类型的格式化数据

具体操作流程请查阅资料,另需要对用jar包支持。

4.Jackson 的JsonNode对象(树模型)

Read JsonNode From JSON从JSON中读取JsonNode

String json = "{ \"f1\" : \"v1\" } ";ObjectMapper objectMapper = new ObjectMapper();JsonNode jsonNode = objectMapper.readTree(json);System.out.println(jsonNode.get("f1").asText());

Write JsonNode to JSON写JsonNode到JSON中

ObjectMapper objectMapper = new ObjectMapper();JsonNode jsonNode = readJsonIntoJsonNode();String json = objectMapper.writeValueAsString(jsonNode);

Get JsonNode Field取得JsonNode的成员和成员值

//取得成员JsonNode field1 = jsonNode.get("field1");//取得成员值String f2Str = jsonNode.get("f2").asText();double f2Dbl = jsonNode.get("f2").asDouble();int    f2Int = jsonNode.get("f2").asInt();long   f2Lng = jsonNode.get("f2").asLong();

5.Jackson JsonParser json解析器

String carJson =        "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";JsonFactory factory = new JsonFactory();JsonParser  parser  = factory.createParser(carJson);Car car = new Car();while(!parser.isClosed()){    JsonToken jsonToken = parser.nextToken();    if(JsonToken.FIELD_NAME.equals(jsonToken)){        String fieldName = parser.getCurrentName();        System.out.println(fieldName);        jsonToken = parser.nextToken();        if("brand".equals(fieldName)){            car.brand = parser.getValueAsString();        } else if ("doors".equals(fieldName)){            car.doors = parser.getValueAsInt();        }    }}System.out.println("car.brand = " + car.brand);System.out.println("car.doors = " + car.doors);

6.Jackson JsonParser json生产器

JsonFactory factory = new JsonFactory();JsonGenerator generator = factory.createGenerator(    new File("data/output.json"), JsonEncoding.UTF8);generator.writeStartObject();generator.writeStringField("brand", "Mercedes");generator.writeNumberField("doors", 5);generator.writeEndObject();generator.close();

6.Jackson Annotations Jackson 注解

Read + Write Annotations读和写注解

@JsonIgnore:忽略属性import com.fasterxml.jackson.annotation.JsonIgnore;public class PersonIgnore {   @JsonIgnore    public long    personId = 0;    public String  name = null;}@JsonIgnoreProperties:忽略属性组import com.fasterxml.jackson.annotation.JsonIgnoreProperties;@JsonIgnoreProperties({"firstName", "lastName"})public class PersonIgnoreProperties {    public long    personId = 0;    public String  firstName = null;    public String  lastName  = null;}@JsonIgnoreType:忽略属性的类型import com.fasterxml.jackson.annotation.JsonIgnoreType;public class PersonIgnoreType {    @JsonIgnoreType    public static class Address {        public String streetName  = null;        public String houseNumber = null;        public String zipCode     = null;        public String city        = null;        public String country     = null;    }    public long    personId = 0;    public String  name = null;    public Address address = null;}@JsonAutoDetect:json自动检查import com.fasterxml.jackson.annotation.JsonAutoDetect;@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY )public class PersonAutoDetect {    private long  personId = 123;    public String name     = null;}

Read Annotations读注解

@JsonSetter:设置自定义名称@JsonAnySetter@JsonCreator@JacksonInject@JsonDeserialize

Write Annotations写注解

@JsonGetter:自定义写值@JsonInclude@JsonAnyGetter@JsonPropertyOrder@JsonRawValue@JsonValue@JsonSerialize

转载地址:http://gwtkx.baihongyu.com/

你可能感兴趣的文章
iOS 绕过相册权限漏洞
查看>>
我的友情链接
查看>>
XP 安装ORACLE
查看>>
八、 vSphere 6.7 U1(八):分布式交换机配置(vMotion迁移网段)
查看>>
[转载] 中华典故故事(孙刚)——19 万岁
查看>>
修改hosts文件里面的主机名,oralce asm无法启动
查看>>
Maven学习总结(十)——使用Maven编译项目gbk的不可映射问题
查看>>
php5编译安装常见错误和解决办法集锦
查看>>
Linux远程访问及控制
查看>>
MongoDB实战系列之五:mongodb的分片配置
查看>>
Unable to determine local host from URL REPOSITORY_URL=http://
查看>>
java基础(1)
查看>>
ORACLE配置,修改tnsnames.ora文件实例
查看>>
Workstation服务无法启动导致无法访问文件服务器
查看>>
.Net组件程序设计之远程调用(二)
查看>>
ant中文教程
查看>>
Linux常用命令(一)
查看>>
WSUS数据库远端存储条件下切换域及数据库迁移
查看>>
【VMCloud云平台】SCAP(四)租户(一)
查看>>
linux释放内存的方法
查看>>