本文主要是介绍Java json gson,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Java json gson
参考:
介绍 JSON:http://www.json.org/json-zh.html
google/gson:https://github.com/google/gson
https://github.com/google/gson:https://github.com/zzz40500/GsonFormat/
Gson 2.8.0 API:http://www.javadoc.io/doc/com.google.code.gson/gson/2.8.0
zzz40500/GsonFormat:https://github.com/zzz40500/GsonFormat
json
(JavaScript Object Notation
)是轻量级的数据交换格式,在数据交换领域中有着广泛的使用
gson
是由 Google
开源的基于 Java
语言的处理 json
格式文件的框架
下面介绍在 Java
语言环境下使用 gson
库来处理 json
格式文件
要实现的功能:
- 在
android studio
/intellij idea
中gson
库的导入; - 解析
json
字符串为类对象,并反之; - 解析
json
字符串为列表,并反之; - 读取本地
json
文件并解析为类对象(或列表); - 将类对象(或列表)写入本地
json
文件; - 复杂
json
格式字符串的解析; - 复杂
json
文件的解析; android sutdio
/intellij idea
插件GsonFormat
介绍;
在 android studio
/ intellij idea
中 gson
库的导入
首先介绍 android studio
中如何导入 gson
依赖
打开 android studio
,新建一个工程:
- 菜单栏
File
->Project Structure
- 在打开的对话框中,左侧选择
app
选项,右侧选择Dependencies
选项
- 点击右上角的 按钮,选择
1. Library Dependency
选项
- 输入
gson
,点击搜索按钮进行搜索,在搜索到的选项中选择com.google.code.gson:gson
,点击OK
按钮,即可加入工程依赖中
接下来介绍 intellij idea
中如何导入 gson
库
下载一个 gson.jar
文件:
Index of /maven2/com/google/code/gson/gson/
打开 intellij idea
,新建一个 java
工程
同样,点击
File
->Project Structure
,打开工程配置框右侧选择
Libraries
选项,左侧选择 按钮,在下拉框中选择Java
选项
- 指定下载好的
gson.jar
文件,点击OK
按钮即可导入gson
库
解析 json
字符串为类对象,并反之
首先,解析 json
字符串为类对象
最简单的 json
字符串
{"name": "zj","age": 18,"address": "china"
}
定义相对应的类:
/*** Created by Lenovo on 2017/2/25.*/
public class GsonTest {String name;int age;String address;public GsonTest(String name, int age, String address) {this.name = name;this.age = age;this.address = address;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "GsonTest{" +"name='" + name + '\'' +", age=" + age +", address='" + address + '\'' +'}';}
}
实现代码下:
import com.google.gson.Gson;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");String str = "{'name':'zj', 'age':18, 'address':'china'}";Gson gson = new Gson();GsonTest test = gson.fromJson(str, GsonTest.class);System.out.println(test.getName());System.out.println(test.getAge());System.out.println(test.getAddress());}
}
结果:
关键函数:gson.fromJson
,有两个参数,前者输入 json
格式字符串,后者输入相对应的类
接下来,将类对象解析为 json
格式字符串
实现代码如下:
import com.google.gson.Gson;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");GsonTest gsonTest = new GsonTest("hello", 222, "World");Gson gson = new Gson();String str = gson.toJson(gsonTest);System.out.println(str);}
}
结果:
关键函数:gson.tojson
,输入类对象即可生成对应的 json
格式字符串
解析 json
字符串为列表,并反之
首先,解析 json
字符串为列表
* json
字符串如下*
[{"name": "one","age": 12,"address": "china"},{"name": "two","age": 22,"address": "english"},{"name": "three","age": 99,"address": "france"}
]
实现代码:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;import java.util.ArrayList;
import java.util.List;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");String str = "[{'name':'one', 'age':12, 'address':'china'}, " +"{'name':'two', 'age':22, 'address':'english'}, {'name':'three', 'age':99, 'address':'france'}]";Gson gson = new Gson();List<GsonTest> gsonTestList = gson.fromJson(str, new TypeToken<List<GsonTest>>(){}.getType());for (GsonTest gsonTest : gsonTestList) {System.out.println(gsonTest.toString());}}
}
结果:
关键函数: gson.fromJson(str, new TypeToken<List<GsonTest>>(){}.getType())
接下来,将类列表,解析为 json
格式字符串
实现代码:
import com.google.gson.Gson;import java.util.ArrayList;
import java.util.List;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");List<GsonTest> gsonTestList = new ArrayList<>();GsonTest gsonTest1 = new GsonTest("monday", 1, "china");gsonTestList.add(gsonTest1);GsonTest gsonTest2 = new GsonTest("thursday", 32, "china");gsonTestList.add(gsonTest2);GsonTest gsonTest3 = new GsonTest("friday", 13, "china");gsonTestList.add(gsonTest3);Gson gson = new Gson();String str = gson.toJson(gsonTestList);System.out.println(str);}
}
结果:
读取本地 json
文件并解析为类对象(或列表)
*这里增加了一个读取本地文件的过程,有两种不同的方式:
1. 即先将本地 json
文件读取为字符串,再使用 gson
库进行解析;
2. 使用 gson
库内置的 JsonReader
来读取 json
文件*
首先,使用第一种方式
文件内容如下:
{"name": "zj","age": 18,"address": "china" }
实现代码:
import com.google.gson.Gson;import java.io.*;public class Main {public static void main(String[] args) {// System.out.println("Hello World!");File file = new File("C:\\JavaProjects\\gson1.json");StringBuilder stringBuilder = new StringBuilder();try {System.out.println("以字符为单位读取文件内容,一次读一个字节:");// 一次读一个字符Reader reader = new InputStreamReader(new FileInputStream(file));int tempchar;while ((tempchar = reader.read()) != -1) {// 对于windows下,\r\n这两个字符在一起时,表示一个换行。// 但如果这两个字符分开显示时,会换两次行。// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。if (((char) tempchar) != '\r') {System.out.print((char) tempchar);stringBuilder.append((char) tempchar);}}System.out.println();reader.close();} catch (Exception e) {e.printStackTrace();}String str = stringBuilder.toString();System.out.println(str);Gson gson = new Gson();GsonTest gsonTest = gson.fromJson(str, GsonTest.class);System.out.println(gsonTest.toString());}}
参考:[Java]读取文件方法大全
结果:
文件内容:
[{"name": "one","age": 12,"address": "china"},{"name": "two","age": 22,"address": "english"},{"name": "three","age": 99,"address": "france"} ]
实现代码:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;import java.io.*;
import java.util.List;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");File file = new File("C:\\JavaProjects\\gson1.json");StringBuilder stringBuilder = new StringBuilder();try {System.out.println("以字符为单位读取文件内容,一次读一个字节:");// 一次读一个字符Reader reader = new InputStreamReader(new FileInputStream(file));int tempchar;while ((tempchar = reader.read()) != -1) {// 对于windows下,\r\n这两个字符在一起时,表示一个换行。// 但如果这两个字符分开显示时,会换两次行。// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。if (((char) tempchar) != '\r') {System.out.print((char) tempchar);stringBuilder.append((char) tempchar);}}System.out.println();reader.close();} catch (Exception e) {e.printStackTrace();}String str = stringBuilder.toString();
// System.out.println(str);Gson gson = new Gson();List<GsonTest> gsonTestList = gson.fromJson(str, new TypeToken<List<GsonTest>>(){}.getType());for (GsonTest gsonTest: gsonTestList) {System.out.println(gsonTest.toString());}}
}
结果:
接下来,使用 JsonReader
来读取 json
文件
在 gson
文档中对于 JsonReader
的讲解:
对于简单文件解析如下
import com.google.gson.Gson; import com.google.gson.stream.JsonReader;import java.io.*;public class Main {public static void main(String[] args) { // System.out.println("Hello World!");Gson gson = new Gson();File file = new File("C:\\JavaProjects\\gson.json");GsonTest gsonTest = new GsonTest(null, -1, null);try {FileInputStream fis = new FileInputStream(file);JsonReader reader = new JsonReader(new InputStreamReader(fis, "UTF-8"));reader.beginObject();while (reader.hasNext()) {String readName = reader.nextName();if (readName.equals("name")) {gsonTest.setName(reader.nextString());} else if (readName.equals("age")) {gsonTest.setAge(reader.nextInt());} else if (readName.equals("address")) {gsonTest.setAddress(reader.nextString());} else {reader.skipValue();}}reader.endObject();reader.close();fis.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (UnsupportedEncodingException e2) {e2.printStackTrace();} catch (IOException e3) {e3.printStackTrace();}System.out.println(gsonTest.toString());} }
运行结果如下:
对于列表的解析
import com.google.gson.Gson; import com.google.gson.stream.JsonReader;import java.io.*; import java.util.ArrayList; import java.util.List;public class Main {public static void main(String[] args) { // System.out.println("Hello World!");Gson gson = new Gson();File file = new File("C:\\JavaProjects\\gson.json");List<GsonTest> gsonTestList = new ArrayList<>();try {FileInputStream fis = new FileInputStream(file);gsonTestList = new Main().readJsonStream(fis);fis.close();} catch (IOException e2) {e2.printStackTrace();}for (GsonTest gsonTest : gsonTestList) {System.out.println(gsonTest.toString());}}public List<GsonTest> readJsonStream(InputStream in) throws IOException {JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));try {return readMessagesArray(reader);} finally {reader.close();}}public List<GsonTest> readMessagesArray(JsonReader reader) throws IOException {List<GsonTest> messages = new ArrayList<GsonTest>();reader.beginArray();while (reader.hasNext()) {messages.add(readMessage(reader));}reader.endArray();return messages;}public GsonTest readMessage(JsonReader reader) throws IOException {String name = null;int age = -1;String address = null;reader.beginObject();while (reader.hasNext()) {String readerName = reader.nextName();if (readerName.equals("id")) {name = reader.nextString();} else if (readerName.equals("age")) {age = reader.nextInt();} else if (readerName.equals("address")) {address = reader.nextString();} else {reader.skipValue();}}reader.endObject();return new GsonTest(name, age, address);} }
运行结果如下:
将类对象(或列表)写入本地 json
文件
*同样的,写过程也会有两种方式:
1. 将类对象(列表)转换为 json
格式字符串后写入 json
文件;
2. 使用 gson
库提供的 JsonWriter
进行写入*
先进行第一种写入
- 写入简单的
json
字符串
实现代码如下:
import com.google.gson.Gson;import java.io.*;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");GsonTest gsonTest = new GsonTest("one", 22, "zj");Gson gson = new Gson();String str = gson.toJson(gsonTest);File file = new File("C:\\JavaProjects\\gson.json");try {FileWriter fileWriter = new FileWriter(file, false);fileWriter.write(str);fileWriter.close();} catch (IOException e) {e.printStackTrace();}}
}
打开 gson.json
文件:
{"name":"one","age":22,"address":"zj"}
- 写入列表
实现代码:
import com.google.gson.Gson;import java.io.*;
import java.util.ArrayList;
import java.util.List;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");List<GsonTest> gsonTestList = new ArrayList<>();GsonTest gsonTest1 = new GsonTest("one", 22, "zj");gsonTestList.add(gsonTest1);GsonTest gsonTest2 = new GsonTest("add", 332, "zj");gsonTestList.add(gsonTest2);GsonTest gsonTest3 = new GsonTest("gadc", 7768, "zj");gsonTestList.add(gsonTest3);Gson gson = new Gson();String str = gson.toJson(gsonTestList);File file = new File("C:\\JavaProjects\\gson.json");try {FileWriter fileWriter = new FileWriter(file, false);fileWriter.write(str);fileWriter.close();} catch (IOException e) {e.printStackTrace();}}
}
实现结果:
[{"name":"one","age":22,"address":"zj"},{"name":"add","age":332,"address":"zj"},{"name":"gadc","age":7768,"address":"zj"}]
接下来,使用 JsonWriter
进行写入
- 简单
json
:
实现代码:
import com.google.gson.Gson;
import com.google.gson.stream.JsonWriter;import java.io.*;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");GsonTest gsonTest = new GsonTest("one", 22, "zj");Gson gson = new Gson();File file = new File("C:\\JavaProjects\\gson.json");try {FileOutputStream fos = new FileOutputStream(file);JsonWriter writer = new JsonWriter(new OutputStreamWriter(fos, "UTF-8"));writer.setIndent(" "); writer.beginObject();writer.name("name").value(gsonTest.getName());writer.name("age").value(gsonTest.getAge());writer.name("address").value(gsonTest.getAddress());writer.endObject();writer.close();fos.close();} catch (IOException e) {e.printStackTrace();}}
}
运行结果如下:
- 简单
json
列表
实现代码:
import com.google.gson.Gson;
import com.google.gson.stream.JsonWriter;import java.io.*;
import java.util.ArrayList;
import java.util.List;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");List<GsonTest> gsonTestList = new ArrayList<>();GsonTest gsonTest1 = new GsonTest("one", 22, "zj");gsonTestList.add(gsonTest1);GsonTest gsonTest2 = new GsonTest("add", 332, "zj");gsonTestList.add(gsonTest2);GsonTest gsonTest3 = new GsonTest("gadc", 7768, "zj");gsonTestList.add(gsonTest3);Gson gson = new Gson();File file = new File("C:\\JavaProjects\\gson.json");try {FileOutputStream fos = new FileOutputStream(file);new Main().writeJsonStream(fos, gsonTestList);fos.close();} catch (IOException e) {e.printStackTrace();}}public void writeJsonStream(OutputStream out, List<GsonTest> messages) throws IOException {JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));writer.setIndent(" ");writeMessagesArray(writer, messages);writer.close();}public void writeMessagesArray(JsonWriter writer, List<GsonTest> messages) throws IOException {writer.beginArray();for (GsonTest message : messages) {writeMessage(writer, message);}writer.endArray();}public void writeMessage(JsonWriter writer, GsonTest message) throws IOException {writer.beginObject();writer.name("name").value(message.getName());writer.name("age").value(message.age);writer.name("address").value(message.address);writer.endObject();}
}
实现结果:
复杂 json
格式字符串的解析
复杂的 json
格式,比如数组,嵌套类等
先介绍一个单个对象的 json
字符串:
{"id": 24324,"text": "zzz","geo": [132,231],"user": {"name": "zj","count": 23.41}
}
包括了值为数组和值为嵌套类的形式
相对应的类对象为:
User.java:
/*** Created by Lenovo on 2017/2/25.*/
public class User {String name;float count;public User(String name, float count) {this.name = name;this.count = count;}public String getName() {return name;}public void setName(String name) {this.name = name;}public float getCount() {return count;}public void setCount(float count) {this.count = count;}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +", count=" + count +'}';}
}
Message.java:
import java.util.Arrays;/*** Created by Lenovo on 2017/2/25.*/
public class Message {int id;String text;int[] geo;User user;public Message(int id, String text, int[] geo, User user) {this.id = id;this.text = text;this.geo = geo;this.user = user;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getText() {return text;}public void setText(String text) {this.text = text;}public int[] getGeo() {return geo;}public void setGeo(int[] geo) {this.geo = geo;}public User getUser() {return user;}public void setUser(User user) {this.user = user;}@Overridepublic String toString() {return "Message{" +"id=" + id +", text='" + text + '\'' +", geo=" + Arrays.toString(geo) +", user=" + user +'}';}
}
- 将
json
字符串转换为类对象:
实现代码:
import com.google.gson.Gson;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");String str = "{'id':24324, 'text':'zzz', 'geo':[132, 231], 'user':{'name':'zj', 'count':13.13}}";Gson gson = new Gson();Message message = gson.fromJson(str, Message.class);System.out.println(str);System.out.println(message.toString());}
}
实现结果:
所以,依旧使用 gson.fromjson
函数即可
- 将类对象转换为
json
字符串:
实现代码:
import com.google.gson.Gson;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");Gson gson = new Gson();Message message = new Message(99, "adf", new int[]{1, 2}, new User("zj", (float)23.23));String str = gson.toJson(message);System.out.println(str);System.out.println(message.toString());}
}
运行结果:
接下来介绍列表的使用情况
json
列表内容如下:
[{"id": 91201,"text": "How do I stream JSON in Java?","geo": null,"user": {"name": "json_newb","count": 41}},{"id": 91902,"text": "@json_newb just use JsonWriter!","geo": [50,-104],"user": {"name": "jesse","count": 2}}
]
- 将
json
字符串转换为列表
实现代码:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;import java.util.List;public class Main {public static void main(String[] args) {
// System.out.println("Hello World!");String str = "[{'id':91201,'text': 'How do I stream JSON in Java?','geo': null,'user':{'name':'json_newb','count':41}}," +"{'id':9128902, 'text': '@json_newb just use JsonWriter!', 'geo': [ 50,-104],'user': {'name': 'jesse','count': 2}}]";Gson gson = new Gson();List<Message> messageList = gson.fromJson(str, new TypeToken<List<Message>>(){}.getType());for (Message message : messageList) {System.out.println(message.toString());}}
}
结果:
复杂 json
文件的解析
其实主要是 JsonReader
和 JsonWriter
对于数组,嵌套类的解析方式
gson
文档中有对应的代码,直接贴上来了
json
内容格式:
[{"id": 912345678901,"text": "How do I read a JSON stream in Java?","geo": null,"user": {"name": "json_newb","followers_count": 41}},{"id": 912345678902,"text": "@json_newb just use JsonReader!","geo": [50.454722, -104.606667],"user": {"name": "jesse","followers_count": 2}}]
JsonReader
使用:
public List<Message> readJsonStream(InputStream in) throws IOException {JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));try {return readMessagesArray(reader);} finally {reader.close();}}public List<Message> readMessagesArray(JsonReader reader) throws IOException {List<Message> messages = new ArrayList<Message>();reader.beginArray();while (reader.hasNext()) {messages.add(readMessage(reader));}reader.endArray();return messages;}public Message readMessage(JsonReader reader) throws IOException {long id = -1;String text = null;User user = null;List<Double> geo = null;reader.beginObject();while (reader.hasNext()) {String name = reader.nextName();if (name.equals("id")) {id = reader.nextLong();} else if (name.equals("text")) {text = reader.nextString();} else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {geo = readDoublesArray(reader);} else if (name.equals("user")) {user = readUser(reader);} else {reader.skipValue();}}reader.endObject();return new Message(id, text, user, geo);}public List<Double> readDoublesArray(JsonReader reader) throws IOException {List<Double> doubles = new ArrayList<Double>();reader.beginArray();while (reader.hasNext()) {doubles.add(reader.nextDouble());}reader.endArray();return doubles;}public User readUser(JsonReader reader) throws IOException {String username = null;int followersCount = -1;reader.beginObject();while (reader.hasNext()) {String name = reader.nextName();if (name.equals("name")) {username = reader.nextString();} else if (name.equals("followers_count")) {followersCount = reader.nextInt();} else {reader.skipValue();}}reader.endObject();return new User(username, followersCount);}
对于列表而言,增加了 reader.beginArray
, reader.hasNext
等函数
JsonWriter
使用:
public void writeJsonStream(OutputStream out, List<Message> messages) throws IOException {JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));writer.setIndent(" ");writeMessagesArray(writer, messages);writer.close();}public void writeMessagesArray(JsonWriter writer, List<Message> messages) throws IOException {writer.beginArray();for (Message message : messages) {writeMessage(writer, message);}writer.endArray();}public void writeMessage(JsonWriter writer, Message message) throws IOException {writer.beginObject();writer.name("id").value(message.getId());writer.name("text").value(message.getText());if (message.getGeo() != null) {writer.name("geo");writeDoublesArray(writer, message.getGeo());} else {writer.name("geo").nullValue();}writer.name("user");writeUser(writer, message.getUser());writer.endObject();}public void writeUser(JsonWriter writer, User user) throws IOException {writer.beginObject();writer.name("name").value(user.getName());writer.name("followers_count").value(user.getFollowersCount());writer.endObject();}public void writeDoublesArray(JsonWriter writer, List<Double> doubles) throws IOException {writer.beginArray();for (Double value : doubles) {writer.value(value);}writer.endArray();}
同样的,对于 JsonWriter
,也增加了 writer.beginArray
等函数,同时要判断数组是否为空的情况
android sutdio
/ intellij idea
插件 GsonFormat
介绍
这是一个根据JSONObject格式的字符串,自动生成实体类参数的插件
android studio
和 intellij idea
的安装都差不多,打开程序,新建工程
点击 File
-> Settings
, 左侧选择 Plugins
,在右侧输入 GsonFormat
:
如果不存在,则点击右侧下方的 Browse Repositories
,进行安装即可
使用方法可查看 github
官网,中文简介在下面:
https://github.com/zzz40500/GsonFormat/blob/master/README_CN.md
这篇关于Java json gson的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!