简体   繁体   English

将 Java 枚举序列化为 XML 的最佳做法是什么?

[英]What is best practice for serializing Java enums to XML?

Hi I have a Java enum and I want serialize a variable containing an enum value back and forth from XML for persistence.嗨,我有一个 Java 枚举,我想从 XML 来回序列化一个包含枚举值的变量以保持持久性。 My enum is defined like this...我的枚举是这样定义的......

public enum e_Type
{
    e_Unknown,
    e_Categoric,
    e_Numeric
}

My variable is declared like this...我的变量是这样声明的......

private e_Type type;

I want it to go into an XML tag like this...我希望它像这样将 go 变成 XML 标签...

<type>value</type>

What's the best practice for persisting values of enums in XML?在 XML 中持久化枚举值的最佳实践是什么?

have a look at JAXB annotations, which are part of the JDK:查看 JAXB 注释,它们是 JDK 的一部分:

public static void main(String[] args) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Foo.class);
    StringWriter sw = new StringWriter();
    context.createMarshaller().marshal(new Foo(), sw);
    System.out.println(sw);
}

@XmlRootElement
public static class Foo {
    @XmlElement
    private e_Type type = e_Type.e_Unknown;
}

@XmlEnum
public enum e_Type {
    e_Unknown,
    e_Categoric,
    e_Numeric
}

you can customize the output further, eg if you wanted your external XML representation to be different from your internal java enum item names:您可以进一步自定义 output,例如,如果您希望外部 XML 表示不同于内部 java 枚举项名称:

@XmlEnumValue("UNKNOWN")
e_Unknown

btw: it is a very strong convention to use upper-case names for java classes/enums顺便说一句:对 java 类/枚举使用大写名称是一个非常严格的约定

After getting responses about 3rd party libraries I decided to fix it myself and thought I would post my solution in case anyone else needs to see it.在收到关于 3rd 方库的回复后,我决定自己修复它,并认为我会发布我的解决方案,以防其他人需要看到它。 I just added two static methods to the enum that take care of what to send back and forth to XML...我刚刚在枚举中添加了两个 static 方法来处理来回发送到 XML 的内容......

public enum e_Type
{
    e_Unknown,
    e_Categoric,
    e_Numeric;
    public static e_Type type(String token)
    {
        return e_Type.valueOf(token);
    }
    public static String token(e_Type t)
    {
        return t.name();
    }
}

This is a good approach for me because it means I can call my getters and setters with the type() and token() methods during serialisation/deserialisation.这对我来说是一个好方法,因为这意味着我可以在序列化/反序列化期间使用 type() 和 token() 方法调用我的 getter 和 setter。 I have extended this into all my enums.我已将此扩展到我的所有枚举中。

I have two main problems with using a 3rd party library for something like this:我在使用 3rd 方库时遇到了两个主要问题:

  1. Bloat.膨胀。 That's a lot of sledgehammer for my little nut这对我的小坚果来说是个大锤
  2. Dependency.依赖。 Adding a new 3rd party library means I have to go through licensing and legal checks and ESCROW etc. Really not worth it for 8 lines of code.添加一个新的 3rd 方库意味着我必须通过许可和法律检查以及 ESCROW 等来 go。对于 8 行代码来说真的不值得。

Try with XStream, it's a library to convert object from and into xml, and support enums too.尝试使用 XStream,它是一个将 object 从和 xml 转换为的库,并且也支持枚举。

String xml = xstream.toXML(enumObject);

http://x-stream.github.io/converters.html http://x-stream.github.io/converters.html

Another framework is Simple XML Serialization which is similar to C# XML serialization.另一个框架是简单的 XML 序列化,它类似于 C# XML 序列化。 It can cope with any object graph, including those that contain enums.它可以处理任何 object 图,包括那些包含枚举的图。

Serializer serializer = new Persister();

persister.write(myObject, myOutput);

The serialization of enums uses the final name() method, so that they can always be recovered from XML.枚举的序列化使用最终的 name() 方法,因此它们总是可以从 XML 中恢复。

I like the first approach.我喜欢第一种方法。 There is no need to include third-party libraries for such a simple task.对于这样一个简单的任务,不需要包含第三方库。 However, making the serialized value == the enum constant literal (ie "e_Unknown", "e_Categoric", "e_Numeric") means that if the developer renames the variable names, it makes the stored values unreadable.但是,使序列化值 == 枚举常量字面量(即“e_Unknown”、“e_Categoric”、“e_Numeric”)意味着如果开发人员重命名变量名称,它会使存储的值不可读。 For example, you save e_Unknown in your XML, later rename the constant as UNKNOWN (for sake of nomenclature).例如,您将 e_Unknown 保存在 XML 中,稍后将常量重命名为 UNKNOWN(为了命名)。 You will then be unable to retrieve old values.然后您将无法检索旧值。

Another approach is to assign each enum a business value, and store the business value in the database, so that rename/refactor of constant names does not break old stored values.另一种方法是为每个枚举分配一个业务值,并将业务值存储在数据库中,这样常量名称的重命名/重构就不会破坏旧的存储值。 I've blogged about this issue if you need more clarification: 3 ways to serialize Java Enums如果您需要更多说明,我已经在博客中讨论过这个问题: 3 种方法来序列化 Java 枚举

I would second vote for JAXB 2, and XStream is good too.我会第二次投票给 JAXB 2,XStream 也不错。 Simple looks a lot like XStream for what that's worth.就其价值而言,Simple 看起来很像 XStream。 Also note that use of annotations is optional -- in most cases it can figure out fields and/or methods to use automatically.另请注意,注释的使用是可选的——在大多数情况下,它可以找出自动使用的字段和/或方法。 And you do not need to use XML schemas at all (you can if you want to): many web sites claim you do, but that's wrong (even Simple page claimed something like this).而且您根本不需要使用 XML 模式(如果您愿意,您可以使用):许多 web 网站声称您这样做,但这是错误的(即使是简单的页面也声称是这样的)。

As to external dependencies: if you are running on JDK 1.6, it comes with bundled implemenation of JAXB (not just the API.), While it is bloat that JDK could do without (since not everyone needs it, those who do could just d/l it IMO).至于外部依赖项:如果您在 JDK 1.6 上运行,它附带了 JAXB 的捆绑实现(不仅仅是 API。),虽然它是 JDK 可以做到的(因为不是每个人都需要它,那些需要它的人只能 d /l 它国际海事组织)。 it is nice if you do need it, And implementation is very good.如果您确实需要它很好,并且实施非常好。 very fast (50-70% speed of just raw XML parsing or writing).非常快(仅原始 XML 解析或写入速度的 50-70%)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将XML转换为Java对象的最佳做法是什么? - What is best practice in converting XML to Java object? 最佳实践:Java / XML序列化:如何确定要反序列化的类? - Best practice: Java/XML serialization: how to determine to what class to deserialize? 在Java中序列化枚举是否有很好的替代方案? - Are there good alternatives for serializing enums in Java? 从Java到XML的序列化/反序列化的最佳实践 - Best Practice for Serialize/Deserialize from Java to XML 在 Java 中返回枚举是不好的做法吗? - Is it bad practice to return Enums in Java? 使用Java web-app(web.xml)部署数据库配置(用户名/密码)的最佳做法是什么? - What is the best practice to deploy database config (username/password) with Java web-app (web.xml)? Java Spring Framework,最佳实践,用于在JSP页面中填充面包屑的XML文件或Bean - Java Spring Framework, What is best practice, XML File or Bean for Populating Bread Crumbs in JSP Page 序列化枚举 - Serializing enums 在Java中使用ENUMS验证值组合的最佳方法是什么? - What is the best approach for validating a combination of values using ENUMS in Java? 使用Firebase保存Java Enums的最佳方法是什么? - What is the best way to save Java Enums using Firebase
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM