解释 Java JSON 类库 GSON 基本用法的示例
最编程
2024-03-09 10:53:14
...
GSON这个Java类库可以把Java对象转换成JSON,也可以把JSON字符串转换成一个相等的Java对象。Gson支持任意复杂Java对象包括没有源代码的对象。
其他的json解析库还有json-lib;Jackson;com.alibaba.fastjson
小编还是喜欢Google的Gson。
一、使用场景:
java对象和json字符串的相互转换;日志输出。
例如:
Logger logger = Logger.getLogger(CommonAction.class); Gson g = new Gson(); logger.info(“return:”+g.toJson(map));
二、用法举例:
1.基础用法toJson
toJason()方法将对象转换成Json字符串
Gson gson = new Gson(); List persons = new ArrayList(); String str = gson.toJson(persons);
2.基础用法:fromJson()
Gson提供了fromJson()方法来实现从Json字符串转化为到java实体的方法。
比如json字符串为:
[{“name”:”name0”,”age”:0}]
则:
Person person = gson.fromJson(str, Person.class);
提供两个参数,分别是json字符串以及需要转换对象的类型。
3.避免Unicode转义
例如: {"s":"\u003c"} 我只想简单的打印成这样 {"s":"<"} 解决方案: 我只需要 disable HTML escaping. Gson gson = new
GsonBuilder().disableHtmlEscaping().create();
4.排除某些字段
如果一个类A中含有字段field1,它的父类也含有字段field1,那么A对象toJson的时候,就会发生declares multiple JSON fields named field1。 解决方案1:在类A中去掉字段filed1. 解决方案2:使用Json的@Expose注解 将A类MessageText中需要打印的字段filed1加上注解@Expose 。那么父类中没有加注解的field1就会被排除掉。
Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
5.换属性名字
三、使用示例:
import java.lang.reflect.Type; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.reflect.TypeToken; public class GSonDemo { public static void main(String[] args) { // Gson gson = new Gson(); //设置将类型的属性进行格式转换 Gson gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create(); List<Person> persons = new ArrayList<Person>(); for (int i = 0; i < 10; i++) { Person p = new Person(); p.setName("name" + i); p.setAge(i * 5); p.setInsertTime(new Timestamp(System.currentTimeMillis())); persons.add(p); } String str = gson.toJson(persons); System.out.println(str); List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType()); for(int i = 0; i < ps.size() ; i++) { Person p = ps.get(i); System.out.println(p.toString()); } System.out.println(new Timestamp(System.currentTimeMillis())); } } class Person { private String name; private int age; private Timestamp insertTime; 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 Timestamp getInsertTime() { return insertTime; } public void setInsertTime(Timestamp insertTime) { this.insertTime = insertTime; } @Override public String toString() { return name + "\t" + age + "\t" + insertTime; } } //实现序列化,反序列化接口 class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> { public JsonElement serialize(Timestamp src, Type arg1, JsonSerializationContext arg2) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS"); String dateFormatAsString = format.format(new Date(src.getTime())); return new JsonPrimitive(dateFormatAsString); } public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!(json instanceof JsonPrimitive)) { throw new JsonParseException("The date should be a string value"); } try { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS"); Date date = (Date) format.parse(json.getAsString()); return new Timestamp(date.getTime()); } catch (Exception e) { throw new JsonParseException(e); } } }
推荐阅读
-
一种结构设计模式,允许在对象中动态添加新行为。它通过创建一个封装器来实现这一目的,即把对象放入一个装饰器类中,然后把这个装饰器类放入另一个装饰器类中,以此类推,形成一个封装器链。这样,我们就可以在不改变原始对象的情况下动态添加新行为或修改原始行为。 在 Java 中,实现装饰器设计模式的步骤如下: 定义一个接口或抽象类作为被装饰对象的基类。 公共接口 Component { void operation; } } 在本例中,我们定义了一个名为 Component 的接口,该接口包含一个名为 operation 的抽象方法,该方法定义了被装饰对象的基本行为。 定义一个实现基类方法的具体装饰对象。 公共类 ConcreteComponent 实现 Component { public class ConcreteComponent implements Component { @Override public void operation { System.out.println("ConcreteComponent is doing something...") ; } } 定义一个抽象装饰器类,该类继承于基类,并将装饰对象作为一个属性。 公共抽象类装饰器实现组件 { protected Component 组件 public Decorator(Component component) { this.component = component; } } @Override public void operation { component.operation; } } } 在这个示例中,我们定义了一个名为 Decorator 的抽象类,它继承了 Component 接口,并将被装饰对象作为一个属性。在操作方法中,我们调用了被装饰对象上的同名方法。 定义一个具体的装饰器类,继承自抽象装饰器类并实现增强逻辑。 公共类 ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component 组件) { super(component); } } public void operation { super.operation System.out.println("ConcreteDecoratorA 正在添加新行为......") ; } } 在本例中,我们定义了一个名为 ConcreteDecoratorA 的具体装饰器类,它继承自装饰器抽象类,并实现了操作方法的增强逻辑。在操作方法中,我们首先调用被装饰对象上的同名方法,然后添加新行为。 使用装饰器增强被装饰对象。 公共类 Main { public static void main(String args) { Component 组件 = new ConcreteComponent; component = new ConcreteDecoratorA(component); 组件操作 } } 在这个示例中,我们首先创建了一个被装饰对象 ConcreteComponent,然后通过 ConcreteDecoratorA 类创建了一个装饰器,并将被装饰对象作为参数传递。最后,调用装饰器的操作方法,实现对被装饰对象的增强。 使用场景 在 Java 中,装饰器模式被广泛使用,尤其是在 I/O 中。Java 中的 I/O 库使用装饰器模式实现了不同数据流之间的转换和增强。 让我们打开文件 a.txt,从中读取数据。InputStream 是一个抽象类,FileInputStream 是专门用于读取文件流的子类。BufferedInputStream 是一个支持缓存的数据读取类,可以提高数据读取的效率,具体代码如下: @Test public void testIO throws Exception { InputStream inputStream = new FileInputStream("C:/bbb/a.txt"); // 实现包装 inputStream = new BufferedInputStream(inputStream); byte bytes = new byte[1024]; int len; while((len = inputStream.read(bytes)) != -1){ System.out.println(new String(bytes, 0, len)); } } } } 其中 BufferedInputStream 对读取数据进行了增强。 这样看来,装饰器设计模式和代理模式似乎有点相似,接下来让我们讨论一下它们之间的区别。 第三,与代理模式的区别: 代理模式的目的是控制对对象的访问,它在对象外部提供一个代理对象来控制对原对象的访问。代理对象和原始对象通常实现相同的接口或继承相同的类,以确保两者可以相互替换。 装饰器模式的目的是动态增强对象的功能,而这是通过对象内部的包装器来实现的。在装饰器模式中,装饰器类和被装饰对象通常实现相同的接口或继承自相同的类,以确保两者可以相互替代。装饰器模式也被称为封装器模式。 在代理模式中,代理类附加了与原类无关的功能。
-
解释 Java JSON 类库 GSON 基本用法的示例