108

What is the Java analogue of .NET's XML serialization?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Dmitry Shechtman
  • 6,548
  • 5
  • 26
  • 25
  • 11
    Ah, the glorious old times when one-liner questions like this one were welcome on SO. So useful. Without all that "What have you tried?"/"Provide details" nonsense people like to read today. – GOTO 0 May 22 '17 at 12:10

11 Answers11

84

2008 Answer The "Official" Java API for this is now JAXB - Java API for XML Binding. See Tutorial by Oracle. The reference implementation lives at http://jaxb.java.net/

2018 Update Note that the Java EE and CORBA Modules are deprecated in SE in JDK9 and to be removed from SE in JDK11. Therefore, to use JAXB it will either need to be in your existing enterprise class environment bundled by your e.g. app server, or you will need to bring it in manually.

Cheekysoft
  • 35,194
  • 20
  • 73
  • 86
71

XStream is pretty good at serializing object to XML without much configuration and money! (it's under BSD license).

We used it in one of our project to replace the plain old java-serialization and it worked almost out of the box.

Boern
  • 7,233
  • 5
  • 55
  • 86
Barak Schiller
  • 1,066
  • 9
  • 9
17

"Simple XML Serialization" Project

You may want to look at the Simple XML Serialization project. It is the closest thing I've found to the System.Xml.Serialization in .Net.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
ARKBAN
  • 3,419
  • 4
  • 24
  • 22
  • It does however require mapping annotations for each field. – mP. Apr 14 '11 at 05:36
  • 1
    Not true, I doesn't require. You can change default behaviour and it will use only present fields. – Konstantin Milyutin Apr 24 '11 at 20:14
  • 1
    I heartily endorse ["Simple"](http://simple.sourceforge.net/) as well. I've used it on a couple of projects with great success. "Simple" is indeed *much* simpler that JAXB. Most appropriate when you have relatively simple needs: Got objects that need to be written to storage to later be re-hydrated as objects again. JAXB has far more features and flexibility, but it's an "80/20" kind of thing, most of the time in most projects you may need only the simple subset of features. – Basil Bourque Jul 23 '15 at 20:35
  • Works well if you just want a 1:1 mapping. If your classes evolve and you still need to deserialize old XML, you run into issues because both the documentation and the error messages are somewhat vague. Diagnosing the problem is usually doable, but figuring out how to fix it could take several days. – toolforger May 23 '19 at 07:39
13

JAXB is part of JDK standard edition version 1.6+. So it is FREE and no extra libraries to download and manage. A simple example can be found here

XStream seems to be dead. Last update was on Dec 6 2008. Simple seems as easy and simpler as JAXB but I could not find any licensing information to evaluate it for enterprise use.

so_mv
  • 3,939
  • 5
  • 29
  • 40
  • 5
    XStream is not dead, it is just mature and stable -- meaning there isn't much to add to core functionality. Same is actually true for JAXB reference implementation, not much activity for past couple of years. – StaxMan Jan 07 '11 at 22:14
  • jaxb sucks .. i could not get it work properly ... xstream works much better ... however not great at class structure changes. – mjs Jul 20 '21 at 09:15
8

Worth mentioning that since version 1.4, Java had the classes java.beans.XMLEncoder and java.beans.XMLDecoder. These classes perform XML encoding which is at least very comparable to XML Serialization and in some circumstances might do the trick for you.

If your class sticks to the JavaBeans specification for its getters and setters, this method is straightforward to use and you don't need a schema. With the following caveats:

  • As with normal Java serialization
    • coding and decoding run over a InputStream and OutputStream
    • the process uses the familar writeObject and readObject methods
  • In contrast to normal Java serialization
    • the encoding but also decoding causes constructors and initializers to be invoked
    • encoding and decoding work regardless if your class implements Serializable or not
    • transient modifiers are not taken into account
    • works only for public classes, that have public constructors

For example, take the following declaration:

public class NPair {
  public NPair() { }
  int number1 = 0;
  int number2 = 0;
  public void setNumber1(int value) { number1 = value;}
  public int getNumber1() { return number1; }
  public void setNumber2(int value) { number2 = value; }
  public int getNumber2() {return number2;}
}

Executing this code:

NPair fe = new NPair();
fe.setNumber1(12);
fe.setNumber2(13);
FileOutputStream fos1 = new FileOutputStream("d:\\ser.xml");
java.beans.XMLEncoder xe1 = new java.beans.XMLEncoder(fos1);
xe1.writeObject(fe);
xe1.close();

Would result in the following file:

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_02" class="java.beans.XMLDecoder">
 <object class="NPair">
  <void property="number1">
   <int>12</int>
  </void>
  <void property="number2">
   <int>13</int>
  </void>
 </object>
</java>
Rubydesic
  • 3,386
  • 12
  • 27
Mishax
  • 4,442
  • 5
  • 39
  • 63
  • Be aware that using `java.beans.XMLDecoder` with user supplied data might introduce arbitrary code execution vulnerabilities in your code. – aventurin Sep 10 '18 at 07:44
  • A lot of unnecessary XML is generated by XMLEncoder class. Just look at the bulky output... – Dia Sheikh Jan 18 '21 at 14:26
2

XMLBeans works great if you have a schema for your XML. It creates Java objects for the schema and creates easy to use parse methods.

John Meagher
  • 22,808
  • 14
  • 54
  • 57
0

If you're talking about automatic XML serialization of objects, check out Castor:

Castor is an Open Source data binding framework for Java[tm]. It's the shortest path between Java objects, XML documents and relational tables. Castor provides Java-to-XML binding, Java-to-SQL persistence, and more.

Theo
  • 131,503
  • 21
  • 160
  • 205
0

Usually I use jaxb or XMLBeans if I need to create objects serializable to XML. Now, I can see that XStream might be very useful as it's nonintrusive and has really simple api. I'll play with it soon and probably use it. The only drawback I noticed is that I can't create object's id on my own for cross referencing.

@Barak Schiller
Thanks for posting link to XStream!

Bartosz Bierkowski
  • 2,782
  • 1
  • 19
  • 18
0

if you want a structured solution (like ORM) then JAXB2 is a good solution.

If you want a serialization like DOT NET then you could use Long Term Persistence of JavaBeans Components

The choice depends on use of serialization.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
m.genova
  • 377
  • 6
  • 15
0

Don't forget JiBX.

Cheeso
  • 189,189
  • 101
  • 473
  • 713
-1
public static String genXmlTag(String tagName, String innerXml, String properties )
{
    return String.format("<%s %s>%s</%s>", tagName, properties, innerXml, tagName);
}

public static String genXmlTag(String tagName, String innerXml )
{
    return genXmlTag(tagName, innerXml, "");
}

public static <T> String serializeXML(List<T> list)
{
    String result = "";
    if (list.size() > 0)
    {
        T tmp = list.get(0);
        String clsName = tmp.getClass().getName();
        String[] splitCls = clsName.split("\\.");
        clsName = splitCls[splitCls.length - 1];
        Field[] fields = tmp.getClass().getFields();

        for (T t : list)
        {
            String row = "";
            try {
                for (Field f : fields)
                {
                    Object value = f.get(t);
                    row += genXmlTag(f.getName(), value == null ? "" : value.toString());
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            row = genXmlTag(clsName, row);

            result += row;
        }
    }

    result = genXmlTag("root", result);
    return result;
}
  • Many problems: Reinvention of Class#getSimpleName *** Reinvention of PropertyDescriptor *** Assumes all properties are accessible fields *** Does not cache reflection results (slooow) *** No way to customize anything (e.g. I'd need to replace class and file names) *** No deserialization – toolforger Dec 28 '17 at 06:07