java中处理json的类库_20190311 Java处理JSON的常用类库

1. Gson

1.1. 背景

谷歌

1.2. 简单使用

Gson gson = new Gson();

System.out.println(gson.toJson(1)); // ==> 1

System.out.println(gson.toJson("abcd")); // ==> "abcd"

System.out.println(gson.toJson(new Long(10))); // ==> 10

System.out.println(gson.toJson(new int[]{1})); // ==> [1]

// Deserialization

int int1 = gson.fromJson("1", int.class);

Integer Integer1 = gson.fromJson("1", Integer.class);

Long Long1 = gson.fromJson("1", Long.class);

Boolean Boolean1 = gson.fromJson("false", Boolean.class);

String String1 = gson.fromJson("\"abc\"", String.class);

String[] StringArr1 = gson.fromJson("[abc]", String[].class);

1.3. 更多

2. FastJson

2.1. 背景

阿里巴巴

2.2. 简单使用

String jsonOutput = JSON.toJSONString(listOfPersons);

System.out.println(jsonOutput);

// [{"AGE":15,"DATE OF BIRTH":1552305572514,"FULL NAME":"John Doe"},{"AGE":20,"DATE OF BIRTH":1552305572514,"FULL NAME":"Janette Doe"}]

List people = JSON.parseArray(jsonOutput, Person.class);

System.out.println(people);

2.3. 更多

3. Jackson

3.1. 背景

Spring Boot默认使用

3.2. 简单使用

ObjectMapper mapper = new ObjectMapper();

Friend friend = new Friend("yitian", 25);

// 写为字符串

String text = mapper.writeValueAsString(friend);

// 写为文件

mapper.writeValue(new File("friend.json"), friend);

// 写为字节流

byte[] bytes = mapper.writeValueAsBytes(friend);

System.out.println(text);

// 从字符串中读取

Friend newFriend = mapper.readValue(text, Friend.class);

System.out.println("从字符串中读取:" + newFriend);

// 从字节流中读取

newFriend = mapper.readValue(bytes, Friend.class);

System.out.println("从字节流中读取:" + newFriend);

// 从文件中读取

newFriend = mapper.readValue(new File("friend.json"), Friend.class);

System.out.println("从文件中读取:" + newFriend);

3.3. 更多

4. net.sf.json-lib

4.1. 背景

出现时间早,很多早期项目使用,目前不推荐使用

Maven:

net.sf.json-lib

json-lib

2.4

jdk15

net.sf.json-lib

json-lib

2.4

jdk15-sources

4.2. 简单使用

// 创建JSONObject

JSONObject jsonObject = new JSONObject();

jsonObject.put("username", "lwc");

jsonObject.put("password", "123");

// 打印:1

System.out.println(jsonObject);

// 增加属性,打印:2

jsonObject.element("sex", "男");

System.out.println(jsonObject);

// 根据key返回,打印:3

System.out.println(jsonObject.get("sex"));

// 判读输出对象的类型

boolean isArray = jsonObject.isArray();

boolean isEmpty = jsonObject.isEmpty();

boolean isNullObject = jsonObject.isNullObject();

// 打印:4

System.out.println("是否数组:" + isArray + " 是否空:" + isEmpty + " 是否空对象:" + isNullObject);

// 把JSONArray增加到JSONObject中

JSONArray jsonArray = new JSONArray();

jsonArray.add(0, "lwc");

jsonArray.add(1, "nxj");

// 开始增加

jsonObject.element("student", jsonArray);

// 打印:5

System.out.println(jsonObject);

4.3. 更多

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值