Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ? 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. Thus, converter.asString(new Integer(5)) should return "5", and converter.asObject("5", Integer.class) should return an Integer with the value of 5.
  • Produce output that is human-readable whenever possible.
  • Deal with all common Java data types, including 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. 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 ?".

like image 563
Bugmaster Avatar asked Jan 23 '23 01:01

Bugmaster


1 Answers

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 )

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

like image 121
OscarRyz Avatar answered Jan 25 '23 15:01

OscarRyz