GSON中Java对象与JSON互相转换——(一)
json的转换插件是通过java的一些工具,直接将java对象或集合转换成json字符串。
常用的json转换工具有如下几种:
1)jsonlib
2)Gson:google
3)fastjson:阿里巴巴
------GSON操作简单,只需要一个jar包----------
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAAA3CAIAAAC0MfCzAAAGbklEQVR4nO2c708TZxzA+QP2bu/2Yq8WXgyNMS4TmyxbyH5pjC5LRiAbmGzm5guybIpuhYGOldISq6cUXNL5C4dMRFqdrQusI0jRiT+CP8qq15+09tpyhWopPDJM96L0+pTeXS3pKHf7fvKEXO9736dfkg8P32vuaVEcACRKUaELAID/CpAbkCwgNyBZQG5AsoDcgGQBuQHJIi65TUQRYYrH4xQpK5KR1OIRYSp0XcCqpAByz4a9o+3VltZtltZto+3Vs2HvC6eC3EAOFEDuodbtcwz1fG7y+dzkk4nb17XVL5yalDsFyA3wkn+5BwcHVSoVX3SWcQ03b/SP1E/fU0bvKSK39vv/2HtX98nNtq0327aOndzxbIbhnxvkBnIgz3KbzeaSkpLi4mK+C65p3g+M6SKOnqeu3qeu3qfO8xGqZ5o698RleOIyMONnRts/5p8eb0sSSieOTETRIiA6wJJPuRNmV1RUCMg90LgBBU0CY6BxA/87cMudUtpEgN4AS97kZs2urKwUkPtK/XrkO58YMVcXdeWb0Z8/Gj5SNnykbJgsGybL/lRtshzdbDm62XJ0S0Y238rNXgBdCpAiP3LjZgvLfenbdch9CrlPTd09PNKxOXjnCKIvIvoSoi+hwG8ocBkFjChomrJ1mtXvZGSD3EAO5EdulUpVjKFUKvmu7NuzFtnbw7eaBzVl4bHDyNOJPJ3IcwZN/IImutDEWeTtDt/T9re+x7juZGTztCVJndNeAP97VvqjwHNfr2Gu1w+o3mZGmxDVhqg2RGmRvR3ZO5D9GHL8xNxqMTWXTTpvc2XzrNwE3E8CHKy03F01rxv3b5wc2YusPyKrAlmb0bgSjbegcRX6Wx0aqbuseDfk4DQbAHJjpeW+rdecqSnpqV1/ft8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+mG4VAvYuC3HIPUSsGT+4BR9DxJqvNGfxEQqFGIZxuVwfEt9nTECRsrRP+sTntrgqXh2IQ+6BilczB51BKBTqMRjLa4XbElF5stjMwLK9HMQht8E8srNB89Znu7OOnQ0ag3mk0PUCqwJxyA0AywDkBiQLyA1IFpAbkCwgNyBZQG5AsoDcgGQBuQHJAnIDkgXkBiQLyA1IFpAbkCwgNyBZQG5AsvwLsh+etIhZt0wAAAAASUVORK5CYII=" alt="" />
User.java
package bean; public class User { private String id;
private String name;
private int age;
private String address;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(String id, String name, int age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
} }
1.测试Java对象转JSON(测试结果在后面注释)
操作简单,无论转单个对象还是集合,都是gson.toJson(obj);
package TestJson; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.xml.bind.UnmarshallerHandler; import org.junit.Test; import com.google.gson.Gson; import bean.User; public class Bean2JSON { // 测试单个对象转JSON
@Test
public void test1(){
User user = new User("1", "QIAOZHI",25,"山西太原");
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json); //{"id":"1","name":"QIAOZHI","age":25,"address":"山西太原"}
} // 测试list转JSON
@Test
public void test2(){
List<User> list = new ArrayList<User>();
list.add(new User("1", "QIAOZHI",25,"山西太原"));
list.add(new User("2", "QIAOZHI",25,"山西太原"));
list.add(new User("3", "QIAOZHI",25,"山西太原"));
Gson gson = new Gson();
String json = gson.toJson(list);
System.out.println(json);
// [{"id":"1","name":"QIAOZHI","age":25,"address":"山西太原"},{"id":"2","name":"QIAOZHI","age":25,"address":"山西太原"},{"id":"3","name":"QIAOZHI","age":25,"address":"山西太原"}]
} // 测试map对象转JSON
@Test
public void test3(){
Map<String,User> map = new HashMap<String,User>();
map.put("1", new User("1", "QIAOZHI",25,"山西太原"));
map.put("2", new User("2", "QIAOZHI",25,"山西太原"));
map.put("3", new User("3", "QIAOZHI",25,"山西太原"));
Gson gson = new Gson();
String json = gson.toJson(map);
System.out.println(json);
// {"3":{"id":"3","name":"QIAOZHI","age":25,"address":"山西太原"},"2":{"id":"2","name":"QIAOZHI","age":25,"address":"山西太原"},"1":{"id":"1","name":"QIAOZHI","age":25,"address":"山西太原"}}
} // 测试list<map>对象转JSON
@Test
public void test4(){
List<Map<String,User>> list = new ArrayList<>();
Map<String,User> map1 = new HashMap<String,User>();
Map<String,User> map2 = new HashMap<String,User>();
map1.put("map11", new User("1", "QIAOZHI",25,"山西太原"));
map1.put("map12", new User("2", "QIAOZHI",25,"山西太原"));
map2.put("21", new User("11", "QIAOZHI",25,"山西太原"));
map2.put("22", new User("21", "QIAOZHI",25,"山西太原"));
list.add(map1);
list.add(map2);
Gson gson = new Gson();
String json = gson.toJson(list);
System.out.println(json);
// [{"map12":{"id":"2","name":"QIAOZHI","age":25,"address":"山西太原"},"map11":{"id":"1","name":"QIAOZHI","age":25,"address":"山西太原"}},{"21":{"id":"11","name":"QIAOZHI","age":25,"address":"山西太原"},"22":{"id":"21","name":"QIAOZHI","age":25,"address":"山西太原"}}]
} }
2.测试Json转Java对象与集合(测试结果在后面注释)
package TestJson_GSON; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.junit.Test; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; public class JSON2Bean {
// 测试json转单个对象
@Test
public void test1(){
String json = "{'id':'1','name':'QIAOZHI','age':25,'address':'山西太原'}";
Gson gson = new Gson();
User user = gson.fromJson(json, User.class);
System.out.println(user);
// User [id=1, name=QIAOZHI, age=25, address=山西太原]
} // 测试JSON转list
@SuppressWarnings("unchecked")
@Test
public void test2(){
String json = "[{'id':'1','name':'QIAOZHI','age':25,'address':'山西太原'},{'id':'2','name':'QIAOZHI','age':25,'address':'山西太原'},{'id':'3','name':'QIAOZHI','age':25,'address':'山西太原'}]";
List<User> list = new ArrayList<User>();
Gson gson = new Gson();
list = (List<User>) gson.fromJson(json, new TypeToken<List<User>>(){}.getType());
System.out.println(list);
for(User user:list){
System.out.println(user);
}
// [{id=1, name=QIAOZHI, age=25.0, address=山西太原}, {id=2, name=QIAOZHI, age=25.0, address=山西太原}, {id=3, name=QIAOZHI, age=25.0, address=山西太原}]
System.out.println(list.get(1));
// {id=2, name=QIAOZHI, age=25.0, address=山西太原}
} // 测试JSON转Map
@Test
public void test3(){
String json = "{'3':{'id':'3','name':'QIAOZHI','age':25,'address':'山西太原'},'2':{'id':'2','name':'QIAOZHI','age':25,'address':'山西太原'},'1':{'id':'1','name':'QIAOZHI','age':25,'address':'山西太原'}}";
Map<String,User> map = new HashMap<String,User>();
Gson gson = new Gson();
map = (Map<String,User>) gson.fromJson(json, new TypeToken<Map<String,User>>(){}.getType());
System.out.println(map);
// {3={id=3, name=QIAOZHI, age=25.0, address=山西太原}, 2={id=2, name=QIAOZHI, age=25.0, address=山西太原}, 1={id=1, name=QIAOZHI, age=25.0, address=山西太原}}
User user = map.get("1");
System.out.println(user);
// {id=1, name=QIAOZHI, age=25.0, address=山西太原}
} // 测试JSON转list<map>对象
@SuppressWarnings("unchecked")
@Test
public void test4(){
String json = "[{'map12':{'id':'2','name':'QIAOZHI','age':25,'address':'山西太原'},'map11':{'id':'1','name':'QIAOZHI','age':25,'address':'山西太原'}},{'21':{'id':'11','name':'QIAOZHI','age':25,'address':'山西太原'},'22':{'id':'21','name':'QIAOZHI','age':25,'address':'山西太原'}}]";
List<Map<String,User>> list = new ArrayList<>();
Gson gson = new Gson();
list = gson.fromJson(json, new TypeToken<List<Map<String,User>>>(){}.getType());
System.out.println(list);
// [{map12={id=2, name=QIAOZHI, age=25.0, address=山西太原}, map11={id=1, name=QIAOZHI, age=25.0, address=山西太原}}, {21={id=11, name=QIAOZHI, age=25.0, address=山西太原}, 22={id=21, name=QIAOZHI, age=25.0, address=山西太原}}]
System.out.println(list.get(1));
// {21={id=11, name=QIAOZHI, age=25.0, address=山西太原}, 22={id=21, name=QIAOZHI, age=25.0, address=山西太原}}
}
}
注意:
json转普通的Javabean只需要两个简单的参数,第一个是json字符串,第二个是需要转换对象的类型。
User user = gson.fromJson(json, User.class);
json转集合与map类型需要使用了TypeToken,它是gson提供的数据类型转换器,可以支持各种数据集合类型转换。也就是通知GSON将json转为那种集合
list = (List<User>) gson.fromJson(json, new TypeToken<List<User>>(){}.getType());
map = (Map<String,User>) gson.fromJson(json, new TypeToken<Map<String,User>>(){}.getType());
list = gson.fromJson(json, new TypeToken<List<Map<String,User>>>(){}.getType());
GSON中Java对象与JSON互相转换——(一)的更多相关文章
- Java对象与JSON互相转换jsonlib以及手动创建JSON对象与数组——(二)
首先声明一下,jsonlib转换与GSON相比太差劲了,操作不是一般的繁琐.GSON可以直接转换成各种集合与对象类型.强烈推荐使用GSON.而且GSON一个方法就可以解决,jsonlib转来转去太繁琐 ...
- Json:Java对象和Json文本转换工具类
Json 是一个用于 Java 对象 和 Json 文本 相互转换的工具类. 安装 下载源码 git clone https://github.com/njdi/durian.git 编译源码 cd ...
- json相关类库,java对象与json相互转换
有效选择七个关于Java的JSON开源类库 转自:http://www.open-open.com/lib/view/open1397870197828.html 翻译: (英语原文:http://w ...
- java对象与json串互转
1:java对象与json串转换: java对象—json串: JSONObject JSONStr = JSONObject.fromObject(object); String str = JSO ...
- FastJson、Jackson、Gson进行Java对象转换Json细节处理
前言 Java对象在转json的时候,如果对象里面有属性值为null的话,那么在json序列化的时候要不要序列出来呢?对比以下json转换方式 一.fastJson 1.fastJson在转换java ...
- FastJson、Jackson、Gson进行Java对象转换Json的细节处理
前言 Java对象在转json的时候,如果对象里面有属性值为null的话,那么在json序列化的时候要不要序列出来呢?对比以下json转换方式 一.fastJson 1.fastJson在转换java ...
- Java对象、Json、Xml转换工具Jackson使用
在Java项目中將一个对象转换成一段Json格式的字符串是非常常见的,能够实现这种需求的工具包也比较多,例如Gson.JSON-lib.Jackson等等.本文主要介绍Jackson的使用,Jacks ...
- Java基础97 json插件的使用(java对象和json字符串对象之间的转换)
1.需要用到的包 2.实例 实体类 people package com.shore.entity; /** * @author DSHORE/2019-4-19 * */ public class ...
- Java对象与Json字符串的转换
Java对象与Json字符串的转换 JSON是一种轻量级的数据交换格式,常用于前后端的数据交流 后端 : 前端 Java对象 > JsonString Java对象 < jsonStrin ...
随机推荐
- 博弈论基础知识: 巴什博奕+斐波那契博弈+威佐夫博奕+尼姆博弈(及Staircase)(转)
(一)巴什博奕(Bash Game):只有一堆n个物品,两个人轮流从这堆物品中取物,规定每次至少取一个,最多取m个.最后取光者得胜.若(m+1) | n,则先手必败,否则先手必胜.显然,如果n=m+1 ...
- MT【12】三点坐标求面积
$L_1,L_2$是O发出的两条射线,C是一个常数,一条动直线$l$分别与$L_1,L_2$交于A,B两点.$S_{\Delta ABC}=C$,求A,B的中点D的轨迹方程.(2012北大自主招生) ...
- wordpress 页面显示指定分类文章
首页显示指定分类备份主题文件夹中的 index.php 文件,修改index.php找到如下一行代码:<?php if (have_posts()) : ?>在上面这行代码的前面加上:&l ...
- Python Matplot中文显示完美解决方案
原因与现象 Matplot是一个功能强大的Python图表绘制库,很遗憾目前版本自带的字体库中并不支持中文字体.所以如果在绘制内容中需要显示中文,那么就会显示为方格字符. 解决办法 有一个较为完美的解 ...
- 自学Linux Shell6.3-系统环境变量持久化
点击返回 自学Linux命令行与Shell脚本之路 6.3-系统环境变量持久化 在你登录Linux系统启动一个bash shell时,默认情况下bash在几个文件中查找命令,这几个文件成为启动文件:b ...
- [luogu3979][bzoj3083]遥远的国度
[luogu传送门] [bzoj传送门] 题目描述 zcwwzdjn在追杀十分sb的zhx,而zhx逃入了一个遥远的国度.当zcwwzdjn准备进入遥远的国度继续追杀时,守护神RapiD阻拦了zcww ...
- sharepoint my site setting
参考这个guide : http://technet.microsoft.com/en-us/library/ee624362.aspx User profile service 不能打开, 原因是s ...
- poj3114 Contries in War (tarjan+dijkstra)
缩完点后对每次询问做dijkstra即可 #include<cstdio> #include<cstring> #include<algorithm> #inclu ...
- 【SPOJ283】Naptime
题目大意:给定一个由 N 个点组成的环,点有点权,现从中选出 M 个点,对于顺时针方向来说,每一段被选取的第一个点的点权不计入答案贡献,求选出的最大权值是多少. 题解:首先考虑线性的情况,设 \(dp ...
- 常量引用 const T&
1.引用本身不是对象,只是引用对象的别名,没有内存空间产生 2.引用必须严格类型匹配 3.而常量引用 const T& 可以引用字面值常量及表达式 其实也就是右值,且常量引用的不同与T类型对象 ...