简体   繁体   English

在Java中将对象转换为String的接受实践?

[英]Accepted practice for converting an Object to and from a String in Java?

What is the commonly accepted method for converting arbitrary objects to and from their String representations, assuming that the exact class of the object is known ? 假设已知对象的确切类,将任意对象转换为String表示形式的常用方法是什么? In other words, I need to implement some methods similar to the following: 换句话说,我需要实现一些类似于以下的方法:

public interface Converter {

    /**
     * Convert this object to its String representation.
     */
    public String asString(Object obj);

    /**
     * Take the String representation of an object produced by asString, 
     * and convert it back to an object of the appropriate class.
     */
    public Object asObject(String stringRepresentation, Class clazz);
}

Ideally, the solution should: 理想情况下,解决方案应该:

  • Use the object's built-in toString() functionality, if possible. 如果可能,请使用对象的内置toString()功能。 Thus, converter.asString(new Integer(5)) should return "5", and converter.asObject("5", Integer.class) should return an Integer with the value of 5. 因此,converter.asString(new Integer(5))应返回“5”,而converter.asObject(“5”,Integer.class)应返回值为5的Integer。
  • Produce output that is human-readable whenever possible. 尽可能生成人类可读的输出。
  • Deal with all common Java data types, including java.util.Date . 处理所有常见的Java数据类型,包括java.util.Date。
  • Allow me to plug in conversion functionality for my own, custom classes. 允许我为自己的自定义类插入转换功能。
  • Be reasonably light-weight and efficient. 相当轻巧,高效。

I understand that there are any number of ready-made solutions that do this (such as Google's protocol buffers, for example), and that I could easily implement a one-off solution myself. 我知道有很多现成的解决方案可以做到这一点(例如Google的协议缓冲区),而且我可以自己轻松实现一次性解决方案。 My question is not, "how do I solve this problem", but rather, "which one of the many ready-made solutions is the current industry standard ?". 我的问题不是“我该如何解决这个问题”,而是“许多现成的解决方案中哪一个是当前的行业标准?”。

My question is not, "how do I solve this problem", but rather, "which one of the many ready-made solutions is the current industry standard ?". 我的问题不是“我该如何解决这个问题”,而是“许多现成的解决方案中哪一个是当前的行业标准?”。

None of them have emerged as defacto standard. 它们都没有成为事实上的标准。

The closest you can get it "default" XML serialization mechanism which BTW sucks if you pretend to write them by hand ( and It is good enough when you use them automatically ) 最接近你可以得到它“默认”的XML序列化机制 ,如果你假装用手写它们,BTW很糟糕(当你自动使用它们时它就足够了)

The next thing closest to an standard and that would be for daily usage, would be JSON to Java, but, well, you know, it is not Java Java 接下来最接近标准并且将用于日​​常使用的东西将是JSON到Java,但是,你知道,它不是Java Java

You can look at the svenson library, it converts java objects to json. 您可以查看svenson库,它将java对象转换为json。 Its pretty quick and uses annotations to introduce custom converters. 它非常快,并使用注释来引入自定义转换器。

http://code.google.com/p/svenson/ http://code.google.com/p/svenson/

Not long ago I would have proposed an xml serializer, but after playing with couchdb for a couple of days, I serve a new master... json. 不久前我会提出一个xml序列化程序,但是在使用了couchdb几天之后,我服务了一个新的主人...... json。

Although it is tempting to use or attempt to implement "toString()" as a reversible operation, the purpose of "toString()" is to generate a user-friendly and easily understandable representation of an object, and this goal is often at odds with including enough state information to truly restore the original object. 尽管使用或尝试将“toString()”实现为可逆操作很有诱惑力,但“toString()”的目的是生成一个用户友好且易于理解的对象表示,并且这个目标通常是不一致的。包含足够的状态信息以真正恢复原始对象。

If you are looking to persist an object, using XML, JSON, or binary serialization is probably the best way to go. 如果您希望持久化对象,则使用XML,JSON或二进制序列化可能是最佳方法。 The "toString()" function should report a human-friendly representation of an object (eg "5", "(3,0,2)", "5+6i", "{1, 2, 3, 4, 5, 6}", "{x => y, z => 3}", etc.). “toString()”函数应报告对象的人性化表示(例如“5”,“(3,0,2)”,“5 + 6i”,“{1,2,3,4,5] ,6}“,”{x => y,z => 3}“,等等。 Even in cases where it is possible to completely restore the object from the generated string, the time to write a function to parse each type of (potentially unstructured) text is best conserved via automated XML persistence in favor of time to write the actual application. 即使在可以从生成的字符串中完全恢复对象的情况下,编写函数来解析每种类型(可能是非结构化的)文本的时间最好通过自动XML持久性来保存,这有利于编写实际应用程序的时间。

I would vote for Json as well and then particularly Gson . 我也会投票给Json,然后特别是Gson It handles generic/parameterized objects very well. 它非常好地处理通用/参数化对象。

Alternatively, you can also write a generic object converter which does all of the needed conversions with a little help of reflection, such as this example . 或者,您也可以编写一个通用对象转换器,它可以通过一些反射帮助完成所有需要的转换,例如本例 But if your "API" require that this converter is to be published as an interface to the enduser, then I would only suggest to replace 但是,如果您的“API”要求将此转换器作为最终用户的接口发布,那么我只建议替换

public Object asObject(String stringRepresentation, Class clazz);

by for example 例如

public <T extends Object> T asObject(String stringRepresentation, Class<T> clazz);

so that one doesn't need to cast it afterwards. 这样一个人不需要事后施展它。

I agree with Oscar that XML might be the preferable form here, if you can tolerate large uncompressed file sizes. 我同意Oscar的观点,如果您可以容忍大的未压缩文件大小,那么XML可能是更好的形式。 To elaborate on his answer, in my experience if you write a fairly straightforward utility class you can serialize your objects into XML with not too much work. 为了详细说明他的答案,根据我的经验,如果你编写一个相当简单的实用程序类,你可以将对象序列化为XML而不需要太多工作。 To read them back, I would recommend Apache Digester which does a great job of rule-based interpretation. 要阅读它们,我会推荐Apache Digester,它可以很好地完成基于规则的解释。

I would only opt for other file formats if I cared about performance or file sizes, though I eprsonally in most cases prefer the flexibility of XML. 如果我关心性能或文件大小,我只会选择其他文件格式,尽管在大多数情况下我更喜欢XML的灵活性。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM