Gson vs JAXB保存java对象(对象状态)

时间:2016-02-25 07:53:46

标签: java jaxb gson

我想保存Java对象(对象状态)或使用网络流向其发送另一个应用程序。我提出了两个选择 就像我有这个对象

Note note = new Note();
note.setId(123);
note.setName("Test Name");

1。 GSON

String json = new GsonBuilder().create().toJson(note);
Systme.out.println(json);

2。 JAXB

JAXBContext jaxbContext = JAXBContext
            .newInstance(Note.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(note, sw);
String xmlString = sw.toString();
System.out.println(xmlString);

喜欢 Gson 支持这些

Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdTypeAdapter()).enableComplexMapKeySerialization().serializeNulls().setDateFormat(DateFormat.LONG).setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting().setVersion(1.0).create();

推荐哪一个? 就以下而言:

  1. 版本
  2. 现场命名支持
  3. 公开或忽略字段

1 个答案:

答案 0 :(得分:0)

经过充分研究,我发现 Gson 优于 JAXB

它支持 JAXB 可能没有的许多内容。

  1. Gson 中不需要字段注释,与 JAXB 不同。
  2. Gson 支持,序列化和反序列化通用类型
  3. 使用任意类型的对象序列化和反序列化集合
  4. 自定义序列化和反序列化
  5. 空对象支持
  6. 版本支持
  7. 从序列化和反序列化中排除字段
  8. GSON赢了!!!

    有关详细信息,请阅读Gson doc