json的解析jar包很多,有gson,fastjson,net.sf.json,org.json等等,做为开发人员只要了解一种或2种工具即可,人推荐gson和fastjson,因为gson稳定,容错率好,是goole出的,而且fastjson号称最快,也是不错的选择。
开始之前,先介绍一下json的数据格式,相信大家都见过json格式数据,它的语法是:
1.数据在名称/值对中
2.数据由逗号分隔
3.花括号保存对象
4.方括号保存数组
但现在比如:
{
[{
"id": "h1",
"name": "历史"
},
{
"id": "h2",
"name": "音乐"
}]
}
是不是json格式数据呢??
Gson是把json格式字符串与Java对象转化的,注意,是序列化和反序列化的,命中注定在java里会有一个对象与json数据对应的。可能是基本类型int,boolean等或者是Map,List又或者是自定义类型。
json数据解析,Gson框架里的“Json”的意思都是“json数据或者叫json格式字符串”,比如fromJson()是从Json字符串里解析出对象,toJson()是把对象转成Json字符串,同理JsonParse意思也一样,是Json字符串解析。通过 getAsJsonObject 和 getAsJsonArray 解析成 JsonObject 和 JsonArray。
{
"name": "陈陈",
"age": 24,
"emailAddress": null,
"bookes": ["化学","物理"],
"bookList":[
{"id":"h1","name":"历史"},{"id":"h2","name":"音乐"}
]
}
public class User {
private String name;
private int age;
private String emailAddress;
private String[] bookes = {"化学", "物理"};
private List bookList;
….getter/setter省略
}
public class Book {
private String id;
private String name;
….getter/setter省略
}
@Test
public void testGson() {
try {
Reader reader = new InputStreamReader(JsonToken.class.getResourceAsStream("/com/cy/vo/es1/data.json"), "UTF-8");
Gson gson = new GsonBuilder().create();
User p = gson.fromJson(reader, User.class);
System.out.println(p);
}catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
}
结果是把整个Json数据映射到User对象里。
{
"name": "怪盗kidou",
"age": 24
}
@Test
public void testStr2Map() {
try {
Reader reader = new InputStreamReader(JsonToken.class.getResourceAsStream("/com/cy/vo/es1/data1.json"), "UTF-8");
Gson gson = new GsonBuilder().create();
Map p = gson.fromJson(reader, Map.class);
System.out.println(p);
}catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
}
结果成功映射到Map里。
{ "list":
[
{"id":"h1","name":"历史"},{"id":"h2","name":"音乐"}
]
}
@Test
public void testStr2List2() {
try {
List result = new ArrayList<>();
Reader reader = new InputStreamReader(JsonToken.class.getResourceAsStream("/com/cy/vo/es1/data2.json"), "UTF-8");
Gson gson = new GsonBuilder().create();
//Json的解析类对象
JsonParser parser = new JsonParser();
//获得大括号的引用
JsonObject jsonObject = parser.parse(reader).getAsJsonObject();
//获得中括号的引用
JsonArray jsonArray = jsonObject.getAsJsonArray("list");
//加强for循环遍历JsonArray
for (JsonElement user : jsonArray) {
//使用GSON,直接转成Bean对象
Book book = gson.fromJson(user, Book.class);
//或者用这样形势Book book = gson.fromJson(user, new TypeToken< Book >() {}.getType());
result.add(book);
}
System.out.println(result);
}catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
}
{"status":"200","data":{"token":"xd-adm-f6c39fbb-abab-4d17-95f6-243d90d43590","userInfo":{"acctPk":10,"ipAcctLoginName":"adm","ipPk":9,"ipNmCn":"adm","ipNmEn":"","ipCatCd":"","ipCatNmCn":"","apps":["app1","adm","front"],"roles":["super_admin"],"attrMap":null}}}
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(jsonD).getAsJsonObject();
String str = jsonObject.getAsJsonObject("data").get("token").getAsString();
xd_token = str;
{
"name": "陈二",
"age": 24
}
和
{ "list":
[
{"id":"h1","name":"历史"},{"id":"h2","name":"音乐"}
]
}
@Test
public void merge() {
try {
Reader reader = new InputStreamReader(JsonToken.class.getResourceAsStream("/com/cy/vo/es1/data2.json"), "UTF-8");
Gson gson = new GsonBuilder().create();
//Json的解析类对象
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(reader).getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("list");
Reader reader1 = new InputStreamReader(JsonToken.class.getResourceAsStream("/com/cy/vo/es1/data1.json"), "UTF-8");
JsonObject jsonObject1 = parser.parse(reader1).getAsJsonObject();
jsonObject1.add("newJ", jsonArray);
String str = gson.toJson(jsonObject1);
System.out.println("merge:" + str);
}catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
}
merge: {
"name": "陈二",
"age": 24,
"newJ": [{
"id": "h1",
"name": "历史"
},
{
"id": "h2",
"name": "音乐"
}]
}
一般使用toJson(Object)和toJson(JsonElement)就够了。其它的可以参照API
@Test
public void testGson() {
Gson gson = new Gson();
User user = new User("陈三",24);
String jsonObject = gson.toJson(user);
System.out.println("gson:" + jsonObject.toString());
}
@Test
public void testGson() {
Gson gson = new GsonBuilder().serializeNulls().create();
User user = new User("陈三",24);
String jsonObject = gson.toJson(user);
System.out.println("gson:" + jsonObject.toString());
}
gson:{"name":"陈三","age":24,"emailAddress":null}
默认是如下格式:May 11, 2017 1:25:04 PM
想输出2017-05-11 13:25:04则需要设置:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
@Test
public void testGson() {
Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
User user = new User("陈三",24);
String jsonObject = gson.toJson(user);
System.out.println("gson:" + jsonObject.toString());
}
gson:{"Name":"陈三","Age":24,"EmailAddress":null,"Bookes":["化学","物理"],"BookList":null}
附Gson的工具类
/**
* Class: StringUtils
* Description:String方法类
* Version: 1.0
* Author: Vinda
* Creation date: 2013-6-27
* (C) Copyright 2010-2015 SmarterLogistics.com Corporation Limited.
* All rights reserved.
*/
package yui.comn.util;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.sf.json.JSONNull;
public class GsonUtils {
public static String getJson(Object data) {
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd
// HH:mm:ss.fff").serializeNulls().create();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").serializeNulls().create();
return gson.toJson(data);
}
public static String getDataByKey(Object data, String key) {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").serializeNulls().create();
JsonParser jsonParser = new JsonParser();
String str = "";
if (data instanceof String) {
str = (String) data;
} else {
str = gson.toJson(data);
}
JsonObject jsonObject = jsonParser.parse(str).getAsJsonObject();
JsonElement jsonElement = jsonObject.get(key);
if (null == jsonElement || StringUtils.equals(jsonElement.toString(), "null")) {
return "";
}
String value = (String) jsonElement.getAsString();
return value;
}
public static void main(String[] args) {
Map data = new HashMap<>();
data.put("name", "cy");
data.put("age", null);
String json = getJson(data);
System.out.println(json);
System.out.println("name:" + getDataByKey(json, "name"));
System.out.println("age:" + getDataByKey(json, "age"));
}
}