Gson解析JSON的方法分享
下文笔者讲述Gson解析json的方法及示例分享,如下所示
Gson对外提供两个方法 toJson()和fromJson() 用于对象和JSON之间互相转换例:
toJson()
对象转换为json文件
Gson gson = new Gson(); // 1 java对象转json文件 gson.toJson(obj, new FileWriter("D:\\test.json")); // 2. java对象转json字符串 String json = gson.toJson(obj);
fromJson()JSON转为Java对象
Gson gson = new Gson(); // 1.json文件转java对象 Object object = gson.fromJson(new FileReader("D:\\test.json"), Object.class); // 2.json字符串转java对象 String json = "{'name' : 'java265'}"; Object object = gson.fromJson(json, Staff.class);
Gson解析JSON的示例
1.下载Gson pom.xml <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> 2. Java对象 Staff.java package com.java265; import java.math.BigDecimal; import java.util.Arrays; import java.util.list; import java.util.Map; public class Staff { private String name; private int age; private String[] position; // array private List<String> skills; // list private Map<String, BigDecimal> salary; // map //getters and setters } 3. Java对象到JSON package com.java265; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.FileWriter; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class GsonExample1 { public static void main(String[] args) { // pretty print Gson gson = new GsonBuilder().setPrettyPrinting().create(); Staff staff = createStaffObject(); // Java objects to String String json = gson.toJson(staff); //System.out.println(json); // Java objects to File try (FileWriter writer = new FileWriter("d:\\test\\staff.json")) { gson.toJson(staff, writer); } catch (IOException e) { e.printStackTrace(); } } private static Staff createStaffObject() { Staff staff = new Staff(); staff.setName("java265"); staff.setAge(18); staff.setPosition(new String[]{"CIO", "CTO", "CEO"}); Map<String, BigDecimal> salary = new HashMap() {{ put("2010", new BigDecimal(20000)); put("2012", new BigDecimal(88000)); put("2018", new BigDecimal(62000)); }}; staff.setSalary(salary); staff.setSkills(Arrays.asList("java", "python", "node", "kotlin")); return staff; } } 4. JSON到Java对象 package com.java265; import com.google.gson.Gson; import java.io.FileReader; import java.io.IOException; import java.io.Reader; public class GsonExample2 { public static void main(String[] args) { Gson gson = new Gson(); try (Reader reader = new FileReader("d:\\test\\staff.json")) { // Convert JSON File to Java Object Staff staff = gson.fromJson(reader, Staff.class); // print staff System.out.println(staff); } catch (IOException e) { e.printStackTrace(); } } } ----运行以上代码,将输出以下信息 Staff{name='java265', age=18, position=[CIO,CTO,CEO], skills=[java, python, node, kotlin], salary={2018=62000, 2012=88000, 2010=20000}}
Gson输出美化后的JSON
package com.java265; import com.google.gson.Gson; public class GsonExample3 { public static void main(String[] args) { // compact print Gson gson = new Gson(); String[] lang = {"Java", "Node", "C#", "JavaScript"}; String json = gson.toJson(lang); System.out.println(json); } } ----运行以上代码,将输出以下信息---- ["Java","Node","C#","JavaScript"] //美化后的输出打印 GsonExample4.java package com.java265; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonExample4 { public static void main(String[] args) { // pretty print Gson gson = new GsonBuilder().setPrettyPrinting().create(); String[] lang = {"Java", "Node", "C#", "JavaScript"}; String json = gson.toJson(lang); System.out.println(json); } } ----运行以上代码,将输出以下信息----- [ "Java", "Node", "C#", "JavaScript" ]
Gson不参与序列化字段
GSON默认情况下,transient和static字段将不参与Gson序列化 此时我们可以通过excludeFieldsWithModifiers方法覆盖其默认设置 如: 只设置static修饰的字段不参与Gson序列化 import java.lang.reflect.Modifier; Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .create(); 设置static和transient修饰的字段不参与Gson序列化 Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT) .create(); static和transient修饰的字段参与Gson序列化 Gson gson = new GsonBuilder() .excludeFieldsWithModifiers() .create();
使用@Expose注解字段
Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .create(); 当启用.excludeFieldsWithoutExposeAnnotation()模式 则将排除所有没有@Expose字段 例: import com.google.gson.annotations.Expose; public class Staff { @Expose(serialize = true, deserialize = true) private String name; @Expose private int age; @Expose(serialize = false, deserialize = true) private String[] position; private List<String> skills; private Map<String, BigDecimal> salary; 如果将上述Java对象转换为JSON,则输出将如下所示 { "name": "java265", "age": 18 }
使用ExclusionStrategies接口实现自定义排除字段
例:自定义注释@ExcludeField ExcludeField.java package com.java265; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.Runtime) @Target({ElementType.FIELD}) public @interface ExcludeField { } 一个ExclusionStrategy用于定义应排除或跳过哪些字段。 package com.java265; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; public class CustomExclusionStrategy implements ExclusionStrategy { private final Class<?> typeToSkip; public CustomExclusionStrategy(Class<?> typeToSkip) { this.typeToSkip = typeToSkip; } @Override public boolean shouldSkipField(FieldAttributes f) { // if field name 'salary`, skip if ("salary".equals(f.getName())) { return true; } // if found @ExcludeField, skip if (f.getAnnotation(ExcludeField.class) != null) { return true; } return false; } @Override public boolean shouldSkipClass(Class<?> clazz) { return (clazz == typeToSkip); } } 再次检查staff对象。 Staff.java public class Staff { private String name; private int age; @ExcludeField private String[] position; private List<String> skills; private Map<String, BigDecimal> salary; //启用ExclusionStrategy模式 Gson gson = new GsonBuilder() .setExclusionStrategies(new CustomExclusionStrategy(List.class)) // exclude all List fields. .create(); //字段名salary , @ExcludeField字段和List类型字段将被排除 {"name":"java265","age":18}
空对象支持
null对象字段将被忽略
package com.java265; import com.google.gson.Gson; public class GsonExample5 { public static void main(String[] args) { Gson gson = new Gson(); Staff staff = createStaffObject(); String json = gson.toJson(staff); System.out.println(json); } private static Staff createStaffObject() { Staff staff = new Staff(); staff.setName("java265"); staff.setAge(18); return staff; } } ----运行以上代码,将输出以下信息----- {"name":"java265","age":18}
//显示空值的设置 Gson gson = new GsonBuilder().serializeNulls().create(); {"name":"java265","age":18,"position":null,"skills":null,"salary":null}
JSON字段命名设置
只需使用 @SerializedName 即可以自定义字段名称例
public class Staff { @SerializedName("java265_name") private String name; ----将输出以下信息----- {"java265_name":"abc"}
版本支持
import com.google.gson.annotations.Since; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import java.util.Map; public class Staff { @Since(1.0) private String name; @Since(2.0) private int age; @Since(3.0) private String[] position; private List<String> skills; private Map<String, BigDecimal> salary; 在此示例中,将排除字段position (版本3)。 Gson gson = new GsonBuilder() .serializeNulls() .setVersion(2.0) // version <= 2.0 will be included. .create(); -----运行以上代码,将输出以下信息----- {"name":null,"age":0,"skills":null,"salary":null}
JSON转换为Map
package com.java265; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.Map; public class GsonExample5 { public static void main(String[] args) { Gson gson = new Gson(); String json = "{\"name\":\"java265\", \"age\"18}"; Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType()); map.forEach((x, y) -> System.out.println("key : " + x + " , value : " + y)); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。