Java JSON
本章节我们将为大家介绍如何在 Java 语言中使用 JSON。
类库选择
Java中并没有内置JSON的解析,因此使用JSON需要借助第三方类库。
下面是几个常用的 JSON 解析类库。
以下教程基于 FastJson 讲解。
环境配置
在 Maven 构建的项目中,在pom.xml
文件中加入以下依赖即可。
1 2 3 4 5
| <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
|
编码与解码
编码
从Java变量到 JSON 格式的编码过程如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public void testJson() { JSONObject object = new JSONObject(); object.put("string","string"); object.put("int",2); object.put("boolean",true); List<Integer> integers = Arrays.asList(1,2,3); object.put("list",integers); object.put("null",null);
System.out.println(object); }
|
在上述代码中,首先建立一个 JSON 对象,然后依次添加字符串,整数,布尔值以及数组,最后将其打印为字符串。
输出结果如下:
1
| {"boolean":true,"string":"string","list":[1,2,3],"int":2}
|
解码
从 JSON 对象到 Java 变量的解码过程如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public void testJson2() {
JSONObject object = JSONObject .parseObject("{\"boolean\":true,\"string\":\"string\",\"list\":[1,2,3],\"int\":2}"); String s = object.getString("string"); System.out.println(s); int i = object.getIntValue("int"); System.out.println(i); boolean b = object.getBooleanValue("boolean"); System.out.println(b); List<Integer> integers = JSON.parseArray(object.getJSONArray("list").toJSONString(),Integer.class); integers.forEach(System.out::println); System.out.println(object.getString("null"));
}
|
在上例中,首先从 JSON 格式的字符串中构造一个 JSON 对象,之后依次读取字符串,整数,布尔值以及数组,最后分别打印,打印结果如下:
1 2 3 4 5 6 7
| string 2 true 1 2 3 null
|
JSON 对象与字符串的相互转化
方法 |
作用 |
JSON.parseObject() |
从字符串解析 JSON 对象 |
JSON.parseArray() |
从字符串解析 JSON 数组 |
JSON.toJSONString(obj/array) |
将 JSON 对象或 JSON 数组转化为字符串 |
实例:
1 2 3 4 5 6 7 8
| JSONObject obj = JSON.parseObject("{\"runoob\":\"菜鸟教程\"}");
JSONArray arr = JSON.parseArray("[\"菜鸟教程\",\"RUNOOB\"]\n");
String objStr = JSON.toJSONString(obj);
String arrStr = JSON.toJSONString(arr);
|
Gson的使用
由于最近需要使用Gson,而Gson和fastjson在使用上还是有所区别的,所以今天稍微试一下Gson的使用.
测试代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.annotations.SerializedName;
import java.util.List;
public class GsonTest {
public static void main(String[] args) { Gson gson = new Gson(); JsonParser parser = new JsonParser();
String input = "{\"name\": \"huyanshi\", \"age\": 2}"; User user = gson.fromJson(input, User.class); System.out.println(user.name); System.out.println(user.age);
JsonObject jo = parser.parse(input).getAsJsonObject(); System.out.println(jo.get("name").getAsString()); System.out.println(jo.get("age").getAsInt());
String i1 = "[{\"name\":\"huyanshi\",\"age\":\"12\"},{\"name\":\"huyanshi1\",\"age\":\"122\"}]"; List<User> users = gson.fromJson(i1, new TypeToken<List<User>>() { }.getType()); System.out.println(users.toString());
JsonObject jo1 = new JsonObject(); jo1.addProperty("name", "huyanshi"); jo1.addProperty("age", "12"); System.out.println(jo1.toString());
String a1 = gson.toJson(user); String a2 = gson.toJson(users); System.out.println(a1); System.out.println(a2);
User u = new User(); u.name = "huyan"; u.age = 2; System.out.println(gson.toJson(u)); }
private static class User { @SerializedName(value = "nn") String name; int age;
@Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } } }
|
完。
ChangeLog
2018-11-02 完成
2019-05-16 添加gson
以上皆为个人所思所得,如有错误欢迎评论区指正。
欢迎转载,烦请署名并保留原文链接。
联系邮箱:huyanshi2580@gmail.com
更多学习笔记见个人博客——>呼延十