json解析工具之jackson的常用实例

Jackson 简介:
  解析大的 json 文件速度比较快;Jackson 运行时占用内存比较低,性能比较好;Jackson 有灵活的 API,可以很容易进行扩展和定制。springMVC这样成熟的框架默认也采用的jackson

添加pom依赖:

<dependency> 
	<groupId>com.fasterxml.jackson.core</groupId> 
	<artifactId>jackson-core</artifactId> 
</dependency>

Jackson 的几个常用注解的使用

注解含义用法
@JsonProperty用于属性,把属性的名称序列化时转换为另外一个名称@JsonProperty(“birth_date”)
@JsonIgnore注解用于排除某个属性,这样该属性就不会被Jackson序列化和反序列化@JsonIgnore(“password”)
@JsonFormat用于属性或者方法,把属性的格式序列化时转换成指定的格式@JsonFormat(timezone = “GMT+8”, pattern = “yyyy-MM-dd HH:mm”)
@JsonPropertyOrder用于类,指定属性在序列化时 json 中的顺序@JsonPropertyOrder({ “birth_Date”, “name” })

直接上使用实例(几个比较常用的解析场景):

1、json转对象

ObjectMapper objectMapper = new ObjectMapper();
String carJson = "{\"brand\":\"Mercedes\",\"doors\":5}";
Car car = objectMapper.readValue(carJson, Car.class); //json直接转对象

/实体类
public class Car {
    private String brand = null;
    private int doors = 0;
}

2、从File中读取对象

ObjectMapper objectMapper = new ObjectMapper();
File file = new File("car.json");//文件路径
Car car = objectMapper.readValue(file, Car.class);

3、从JSON数组字符串中读取对象列表

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

4、将json接收为Map

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

5、复杂一点的json,可以直接使用JsonNode

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

参考博文地址:https://www.cnblogs.com/guanbin-529/p/11488869.html

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页