Java基础 : JSON的使用

Java中JSON的使用

概述

JSON是JavaScript Object Notation的缩写,是一种轻量级的数据交换形式,是一种XML的替代方案,而且比XML更小、更快而且更易于解析

Java下常见的JSON类库有Jackson、Google-Gson、JSON-lib、Flexjson、Json-io、Genson、JSONiJ等,其中前三种比较常用

1. JSON的Jackson类库

Jackson为处理JSON格式提供了三种模型的处理方法
1、流式API或者增量解析/产生(Streaming API or incremental parsing/generation): 写JSON内容被作为离散的事件
2、树模型(Tree Model): 提供一个可变内存树表示JSON文档
3、数据绑定(Data binding): 实现JSON与POJO的转换

通常情况下,我们使用第三种模型来进行JSON和实体类对象的相互转化
Jackson的maven依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>
1.1 把实体类对象转化为JSON
import com.fasterxml.jackson.databind.ObjectMapper;

//需要转化为json的实体类
StudentDTO student = new StudentDTO();
student.setId(137L);
student.setName("张三");
student.setAge(23);
//使用ObjectMapper的writeValue方法转化
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(student);
//控制台输出json验证
System.out.println("json : " + json);
1.2 把JSON转换为实体类对象
import com.fasterxml.jackson.databind.ObjectMapper;

//需要转化为实体类的json
String json = {"id":137, "name":"张三", "age": 23}
//使用ObjectMapper的readValue方法转化
ObjectMapper mapper = new ObjectMapper();
StudentDTO student = mapper.readValue(json, StudentDTO.class);
//控制台输出实体类验证
System.out.println("student : " + student.toString);
1.3 初始化ObjectMapper及参数配置
 ObjectMapper mapper = new ObjectMapper();
 //识别json中不带引号的字段名
 mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
  //识别json中不带引号的字段名
 mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

 ObjectMapper objectMapper = new ObjectMapper();
 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
 objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);
 objectMapper.setSerializationInclusion(Include.NON_NULL);
 objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
 objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
1.4 使用ObjectNode转换Map和Sting
ObjectNode jsonNodes1 = objectMapper.createObjectNode();
jsonNodes1.put("cardId", cardId);
jsonNodes1.put("pwd", pwd);

String jsonStr = jsonNodes1.toString();
ObjectNode jsonNodes2 = JSON.parseJsonObject(jsonStr);
String cardId= jsonNodes2.get("cardId").asLong();
String pwd= jsonNodes2.get("pwd").asText();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值