GSON的用法(处理对象和JSON的相互转化):
Gson是Google自己写的一个Java对象与JSON相互转化的工具包,首先我们需要下载jar包,这里可用idea直接下载,下载步骤如下;点击项目结构
点击+号:
点击maven:
然后搜索jar包关键字gson:
下载到项目的指定位置
编写一个JSON文件
[ { "id": 9223232323, "text": "How do I read a JSON stream in Java", "geo": null, "user": { "name": "json_new", "followers_count": 41 } }, { "id": 8787879686, "text": "@Json just use JsonReader", "geo": [ 56.23212323, -1034.343 ], "user": { "name": "java nb", "followers_count": 2 } } ]
所对应的实体类:
package com.lili.json; import java.util.Arrays; import java.util.List; /** * @author: QiJingJing * @create: 2021/7/18 */ public class Message { private long id; private String text; private List<Double> geo; private User user; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public List<Double> getGeo() { return geo; } public void setGeo(List<Double> geo) { this.geo = geo; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Message{" + "id=" + id + ", text='" + text + '\'' + ", geo=" + geo + ", user=" + user + '}'; } }
package com.lili.json; /** * @author: QiJingJing * @create: 2021/7/18 */ public class User { private String name; private int followers_count; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getFollowers_count() { return followers_count; } public void setFollowers_count(int followers_count) { this.followers_count = followers_count; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", followers_count=" + followers_count + '}'; } }
编写代码解析复杂JSON:
public class JsonTest { /** * 使用JsonReader解析一个复杂的json */ @Test public void parseJsonMessages() throws IOException { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/lili/json/message.json"); InputStreamReader reader = new InputStreamReader(is); JsonReader jsonReader = new JsonReader(reader); List<Message> list = new ArrayList<>(); jsonReader.beginArray(); while (jsonReader.hasNext()){ list.add(parseJsonMessage(jsonReader)); } jsonReader.endArray(); System.out.println(Arrays.toString(list.toArray())); } /** * 解析message类的方法 */ private Message parseJsonMessage(JsonReader reader) throws IOException { Message message = null; reader.beginObject(); message = new Message(); while (reader.hasNext()) { String name = reader.nextName(); if("id".equals(name)){ message.setId(reader.nextLong()); }else if("text".equals(name)){ message.setText(reader.nextString()); }else if("geo".equals(name) && reader.peek() != JsonToken.NULL){ message.setGeo(readGeo(reader)); }else if("user".equals(name)){ message.setUser(parseJsonUser(reader)); }else { // 最好加上 reader.skipValue(); } } reader.endObject(); return message; } /** * 解析geo */ private List<Double> readGeo(JsonReader reader) throws IOException { List<Double> list = new ArrayList<>(); reader.beginArray(); while (reader.hasNext()){ list.add(reader.nextDouble()); } reader.endArray(); return list; } /** * 解析user类的方法 */ public User parseJsonUser(JsonReader reader) throws IOException { User user = null; reader.beginObject(); user = new User(); while (reader.hasNext()) { String name = reader.nextName(); if("name".equals(name)){ user.setName(reader.nextString()); }else if("followers_count".equals(name)){ user.setFollowers_count(reader.nextInt()); }else{ // 最好加上 reader.skipValue(); } } reader.endObject(); return user; } }
运行结果:
[Message{id=9223232323, text='How do I read a JSON stream in Java', geo=null, user=User{name='json_new', followers_count=41}}, Message{id=8787879686, text='@Json just use JsonReader', geo=[56.23212323, -1034.343], user=User{name='java nb', followers_count=2}}]
利用Gson工具类将一组JSON对象转换成对象集合,或把对象集合转化为JSON数组:
写一个新的JSON文件:
[ { "firstName": "qi", "lastName": "jing", "email": "2811157481@qq.com" }, { "firstName": "yang", "lastName": "li", "email": "2811157481@qq.com" } ]
对应实体类:
package com.lili.json; /** * @author: QiJingJing * @create: 2021/7/18 */ public class Name { private String firstName; private String lastName; private String email; public Name() { } public Name(String firstName, String lastName, String email) { this.firstName = firstName; this.lastName = lastName; this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "Name{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}'; } }
编写测试代码:
/** * 把一组JSON对象转换成对象集合,或把对象集合转化为JSON数组 */ @Test public void gson2(){ Gson gson = new Gson(); InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/lili/json/name.json"); assert resourceAsStream != null; InputStreamReader reader = new InputStreamReader(resourceAsStream); TypeToken<List<Name>> typeToken = new TypeToken<List<Name>>(){}; List<Name> list = gson.fromJson(reader, typeToken.getType()); System.out.println(list); // 再转回去 String json = gson.toJson(list, typeToken.getType()); System.out.println(json); }
对象集合和json数据如下:
[Name{firstName='qi', lastName='jing', email='2811157481@qq.com'}, Name{firstName='yang', lastName='li', email='2811157481@qq.com'}] [{"firstName":"qi","lastName":"jing","email":"2811157481@qq.com"},{"firstName":"yang","lastName":"li","email":"2811157481@qq.com"}]