java 与 JSON
Java 与 JSON
JSON 是不同程序之间传递信息的一种格式。本文描述了 JSON 在 Java 中的应用。
目前 Java 中比较主流的相关解析工具有谷歌提供的 Gson 和阿里提供的 FastJSON 。
一、JSON 格式
JSON: JavaScript Object Notation(JS对象简谱),是一种轻量级的数据交换格式。
例如一本书,有 id 属性值为 "1001",有 name 属性值为 "book",有 info 属性值为 "简介",用 JSON 表示如下:
{
"id":"1001",
"name":"book",
"info":"简介"
}
另外,JSON 格式中还可以包含数组(用中括号包含[,,,]),对象之间还可以互相嵌套。
例如一个柜子,名字是 "书柜",有一个 "books" 属性包含了三本书,还有一个 belong 属性表示属于某个人,可以表示为:
{
"name":"书柜",
"books":["book1","book2",{
"id":"1001",
"name":"book",
"info":"简介"
}],
"belong":{
"name":"张三",
"age":18,
}
}
二、Java 与 JSON
1. Gson
使用 Gson 类的一个实例可以将一串包含 JSON 的字符串中的数据解析为一个 Java 对象的实例,也可以将一个类的信息保存到一串 JSON 字符串中。
后文中的代码使用的 Book 类和 Cabinet 类如下
class Book {
private int id;
private String name;
private String info;
public String toString() {
return "name:" + name + ", info:" + info;
}
}
class Cabinet {
private String name;
private Book[] books;
private String belong;
public String toString() {
return "Cabinet{" +
"name='" + name + '\'' +
", books=" + Arrays.toString(books) +
", belong='" + belong + '\'' +
'}';
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cabinet cabinet = (Cabinet) o;
return Objects.equals(name, cabinet.name) && Arrays.equals(books, cabinet.books) && Objects.equals(belong, cabinet.belong);
}
public int hashCode() {
int result = Objects.hash(name, belong);
result = 31 * result + Arrays.hashCode(books);
return result;
}
public Cabinet() {}
public Cabinet(String name, Book[] books, String belong) {
this.name = name;
this.books = books;
this.belong = belong;
}
}
- 保存信息: toJson(Object src)方法
- 将一个类保存为 json 格式
import com.google.gson.Gson; public class Demo1 {
public static void main(String[] args) {
// 创建 Gson 对象
Gson gson = new Gson();
Book b = new Book(1001, "book", "info"); // 将一个对象 b 转换为 json 字符串
String s = gson.toJson(b);
System.out.println(s);
}
}
- 将一个集合保存为 json 格式
import com.google.gson.Gson;
import java.util.ArrayList;
public class Demo2 {
public static void main(String[] args) {
// 创建 Gson 对象
Gson gson = new Gson();
ArrayList<Object> list = new ArrayList<>();
list.add("abc");
list.add(new Book(1001, "book", "info"));
// 将一个集合 list 转换为 json 字符串
String s = gson.toJson(list);
System.out.println(s);
}
}
- 将一个复杂的对象用 json 格式保存到文件中
import com.google.gson.Gson;
import java.io.*;
public class Demo3 {
public static void main(String[] args) throws IOException {
// 创建 Gson 对象
Gson gson = new Gson();
// 将一个复杂的对象转换为字符串
String s = gson.toJson(new Cabinet("Cabinet",
new Book[]{new Book(1001, "book1", "info1"),
new Book(1002, "book2", "info2"),
new Book(1003, "book3", "info3")}, "张三"));
// 将获得的字符串写入文件中
FileWriter fw = new FileWriter("cabinet.json");
fw.write(s);
fw.close(); // 记得关闭流!
}
}
- 解析 JSON 字符串: fromJson(String json, Class classOfT) 方法
- 解析一个类
import com.google.gson.Gson;
public class Demo4 {
public static void main(String[] args) {
Gson gson = new Gson();
// {"name":"book","info":"abc"}
Book book = gson.fromJson("{\"name\":\"book\",\"info\":\"abc\"}", Book.class);
System.out.println(book);
}
}
- 解析一个数组
import com.google.gson.Gson;
import java.util.List;
public class Demo5 {
public static void main(String[] args) {
// ["abc","bcd","cde"]
List list = new Gson().fromJson("[\"abc\",\"bcd\",\"cde\"]",List.class);
for (Object s : list) {
System.out.println(s);
}
}
}
- 从文件中解析一个较为复杂的类
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Demo6 {
public static void main(String[] args) throws IOException {
// 此处使用的文件为上面代码中保存的 cabinet.json 文件
// 读取文件中的数据
BufferedReader br = new BufferedReader(new FileReader("cabinet.json"));
String s = br.readLine();
br.close(); // 别忘记关闭!
// 创建 Gson 对象
Gson gson = new Gson();
// 如果我们没有 Cabinet 这个类,则可以转化为 HashMap 对象
HashMap hashMap = gson.fromJson(s, HashMap.class);
// 打印全部
System.out.println(hashMap);
List<Book> list = (List<Book>) hashMap.get("books");
// 打印 books
System.out.println(list.get(1));
}
}
注意:JSON 字符串应该对应好对应类的各个属性名,如果 JSON 字符串中出现了对应类中没有的属性名,那么这个属性将被忽略。同理,如果 JSON 字符串中没有对应类中的属性,那么对应的类的这个属性设置为默认值。
2.FastJSON
使用 FastJSON 解析或保存 JSON 字符串方法:
- 保存信息: toJSONString(Object object)方法
注意:使用 FastJSON 保存的类每个属性必须有 get 方法,否则无法保存。上面的 Book 类没有提供 get 方法,则无法保存。- 保存一个类的信息
import com.alibaba.fastjson.JSON;
public class Demo {
public static void main(String[] args) {
// 假设这个类有提供 get 方法
Book b = new Book(1001, "book", "info");
// 转化为 JSON 字符串
String s = JSON.toJSONString(b);
// 打印出来检查是否正确
System.out.println(s);
}
}
- 保存一个集合(数组)的信息
import com.alibaba.fastjson.JSON;
public class Demo {
public static void main(String[] args) {
// 这里假设 Book 类有提供 get 方法
Book[] b = new Book[]{new Book(1001, "book", "info"), new Book(1002, "abc", "ofni")};
String s = JSON.toJSONString(b);
System.out.println(s);
}
}
- 保存一个较为复杂的类到文件中
import com.alibaba.fastjson.JSON;
import java.io.FileWriter;
import java.io.IOException; public class Demo {
public static void main(String[] args) throws IOException {
Book b1 = new Book(1001, "1", "a");
Book b2 = new Book(1002, "2", "b");
Book b3 = new Book(1003, "3", "c");
Book[] bs = {b1, b2, b3};
Cabinet c = new Cabinet("cabinet", bs, "abc");
String json = JSON.toJSONString(c);
FileWriter fw = new FileWriter("cabinet2.json");
fw.write(json);
fw.close();
}
}
- 解析 JSON 字符串: parseObject(String text, Class clazz) 方法
注意:获取信息的类必须提供 无参构造方法和各个 set 方法,否则会出现 JSONException 异常- 解析得到一个类的信息
import com.alibaba.fastjson.JSON;
public class Demo {
public static void main(String[] args){
// {"id":1001,"name":"b","info":"1"}
Book b = JSON.parseObject("{\"id\":1001,\"name\":\"b\",\"info\":\"1\"}", Book.class);
System.out.println(b);
}
}
- 解析得到一个数组信息
import com.alibaba.fastjson.JSON
import java.io.IOException;
import java.util.List;
public class Demo {
public static void main(String[] args) {
// ["",{"id":123,"name":"abc"},null]
List list = (List) JSON.parse("[\"\",{\"id\":123,\"name\":\"abc\"},null]");
System.out.println(list.get(1));
}
}
- 从文件中解析得到一个较为复杂的对象
import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
public class Demo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("cabinet2.json"));
String s = br.readLine();
HashMap hashMap = JSON.parseObject(s, HashMap.class);
System.out.println(hashMap);
List list = (List) hashMap.get("books");
System.out.println(list.get(1));
HashMap book2 = JSON.parseObject(list.get(1).toString(), HashMap.class);
System.out.println(book2.get("name"));
}
}
java 与 JSON的更多相关文章
- Java集合 Json集合之间的转换
1. Java集合转换成Json集合 关键类:JSONArray jsonArray = JSONArray.fromObject(Object obj); 使用说明:将Java集合对象直接传进JSO ...
- Java对象 json之间的转换(json-lib)
在这里主要简单的介绍一下,如何使用json-lib这个工具包来完成Java对象(或集合)与json对象(或集合)之间的转换~ 1. Java对象转换成json(既创建json) 关键类:JSONObj ...
- Java 的 JSON 开源类库选择比较(zz)
在看了作者的介绍,然后我又到mvnrepository上去看了各个库的的使用数之后,发现只能在jackson和gson之间做选择. 以下是原文 有效选择七个关于Java的JSON开源类库 April ...
- java中json包的使用以及字符串,map,list,自定义对象之间的相互转换
做一个map和字符串的转换,需要导入这些jar包,这是最基本的一些jar包. 经过多方尝试得出结论入下: 首先导入基本包:json-lib-2.2.3-jdk15.jar 如果没有这个jar包,程序是 ...
- java系列--JSON数据的处理
http://blog.csdn.net/qh_java/article/details/38610599 http://www.cnblogs.com/lanxuezaipiao/archive/2 ...
- Java之JSON数据
特别注意:使用JSON前需要导包 操作步骤地址:http://blog.csdn.net/baidu_37107022/article/details/70876993 1.定义 JSON(JavaS ...
- JSON以及Java转换JSON的方法(前后端常用处理方法)
)); map.put("arr", new String[] { "a", "b" }); map.put("func" ...
- java处理json与对象的转化 递归
整个类是一个case,总结了我在使用java处理json的时候遇到的问题,还有级联关系的对象如何遍历,json和对象之间的转换! 对于对象json转换中遇到的问题我参考了一篇博客,http://blo ...
- Java JWT: JSON Web Token
Java JWT: JSON Web Token for Java and Android JJWT aims to be the easiest to use and understand libr ...
- Java解析json字符串和json数组
Java解析json字符串和json数组 public static Map<String, String> getUploadTransactions(String json){ Map ...
随机推荐
- top单核与32C--CPU爆表
linux的cpu使用频率是根据cpu个数和核数决定的 top, 然后你按一下键盘的1,这就是单个核心的负载,不然是所有核心的负载相加,自然会超过100 单核为100%,服务器是32核的,下面基本用了 ...
- tcpdump: error while loading shared libraries: libpcap.so.1: cannot open shared object file: No such file or directory
[root@inner ~]# tcpdump -i any -s 0 -w trunkm.pcaptcpdump: error while loading shared libraries: lib ...
- A表某字段==B表某字段 更新A表的数据
update mls_supplytask t1 -- 供应商认证任务 JOIN mls_sup_cert_report t2 -- 供应商认证报告 on t1.id = t2.certTaskId ...
- C++的右值引用是左值,rvalue reference is lvalue.
参考: https://stackoverflow.com/questions/28483250/rvalue-reference-is-treated-as-an-lvalue
- Uri转绝对路径工具类
/** * 反射从 provider uri中获取 文件绝对路径 * @param context * @param uri * @return */ private static String ge ...
- 特别好用的题库(oj)
tk.hustoj.com 每次做题时,我都会对"外部导入"这四个字感到迷惑: 这些题,究竟是从哪里"导入"的? 我们不为而知...... 直到后来...... ...
- windows11上面打开HEIC文件的有效方法
今天在传资料的时候,用手机拍了一张照片传到window11,打开时竟然无法打开,顿时有点诧异,仔细看了文件类型(HEIC),可能软件不识别,怎么解决呢? 经过搜索整理尝试了许多方法,没找到一个合适的. ...
- go 更新依赖库到最新版本
go 怎么更新依赖库到最新版本 遇到这么一个问题:我自己的一个程序依赖自己写的一个库,然后修改了库,程序这边想要更新库,却怎么也更新不上 删除mod.sum文件里相关库的信息 使用find / -na ...
- 栈和寄存器虚拟机比较(以python和lua为例)
指令长度 python python的指令定长,长度为16bit,其中8bit操作码,8bit操作数. ///@file: Python-3.6.0\Include\code.h typedef ui ...
- Linux下如何排查CPU及内存占用过多
CPU 使用top命令,然后按shift+p按照CPU排序,找到占用CPU过高的进程pid. 使用top -H -p pid命令,找到进程中消耗资源最高的线程ppid. 使用echo 'obase=1 ...