本文共 10450 字,大约阅读时间需要 34 分钟。
JSON解析-Jackson
参考链接:
简介:Jackson是一个简洁的方式去解析JSON开源包。Jackson可以解析JSON从String,Stream,或者file的方式去创建Java对象。Jackson不仅仅可以解析JSON到Java对象,也可以将Java对象解析为JSON字符串。原理:Java反射机制实现JSON和Java对象间数据自动转换。
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
从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();Listcars1 = objectMapper.readValue(jsonArray, new TypeReference
>(){});
从JSON字符串中转换为Java的Map存储
String jsonObject = "{\"brand\":\"ford\", \"doors\":5}";ObjectMapper objectMapper = new ObjectMapper();MapjsonMap = 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包支持。
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();
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);
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();
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/