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 ...
随机推荐
- NodeJs加载站点的所有页面不存在则404
演示 链接:https://pan.baidu.com/s/1TZ351m3wUWZpq46qGbejjg 密码:ijj5 代码: var http = require("http" ...
- Spring IOC和Spring AOP的实现原理(源码主线流程)
写在前面 正本文参考了<spring技术内幕>和spring 4.0.5源码.本文只描述原理流程的主线部分,其他比如验证,缓存什么可以具体参考源码理解. Spring IOC 一.容器初始 ...
- UVa - 10339
It has been said that a watch that is stopped keeps better time than one that loses 1 second per day ...
- Java8的flatMap如何处理有异常的函数
Java8的flatMap函数,作用是:如果有值,为其执行mapping函数返回Optional类型返回值,否则返回空Optional. 见到的映射函数往往都只有一句话,连大括号都不需要加的,如下: ...
- MT【71】数列裂项放缩题
已知${a_n}$满足$a_1=1,a_{n+1}=(1+\frac{1}{n^2+n})a_n.$证明:当$n\in N^+$时, $(1)a_{n+1}>a_n.(2)\frac{2n}{n ...
- 【比赛】NOIP2018 总结
一.考试过程 Day1: 先看了一遍题目,得到的结论是没有题是直接秒掉的,然后一道一道认真看. 看T1的时候开始并没想起来有一道原题,只是脑海中有一个印象,好像求差分和可以.然后自测了一下小样例,发现 ...
- [luogu4264][USACO18FEB]Teleportation
题解 先吐槽一波题目:便便传送门,出题人还真的有一点厉害的滑稽. 废话不多说. 首先问题的本质就是求如果当这个传送门的端点位于\(y\)的时候,最小的求出总代价,我们设为函数\(f(y)\). 因为这 ...
- 关于scrollintoview()真的是有意思极了,结合普通tab切换一起看看
scrollIntoView(alignWithTop) 是html5新特性中的一个元素,他主要是指滚动浏览器窗口或容器元素,以便在当前视窗的可见范围看见当前元素. alignWithTop是true ...
- gcc-linaro-arm-linux-gnueabihf交叉编译器配置
系统Ubuntu14.04 版本:gcc 版本 4.7.3 20130328 (prerelease) (crosstool-NG linaro-1.13.1-4.7-2013.04-20130415 ...
- AE与C#入门笔记
http://www.cnblogs.com/e3e4/articles/3695214.html