XML serialization in Java? [closed]
Asked Answered
O

11

108

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

Overprint answered 30/8, 2008 at 8:33 Comment(1)
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.Joyann
R
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.

Ragout answered 30/8, 2008 at 9:31 Comment(2)
That's right, JAXB is definitely the best option!Anteater
JAXB was removed from standard java distributions as of Java 10, which makes it now a library you must bundle with your application if you want it, unless you're operating in a context that already bundles it for you.Massachusetts
A
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.

Auk answered 30/8, 2008 at 8:55 Comment(4)
Very useful, it can have problems on complecated tree structures such as JGraph with non string node objects though.Esker
Simpler and better then other solutionsHandrail
I like XStream. Only thing is that I don't understand why a character is added before the actual XML.Acidulate
Just tried it. Beat 7 other json serializers that could not serialize and deserialize objects properly.Desberg
D
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.

Davit answered 22/1, 2009 at 14:1 Comment(4)
It does however require mapping annotations for each field.Salas
Not true, I doesn't require. You can change default behaviour and it will use only present fields.Charleencharlemagne
I heartily endorse "Simple" 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.Grievous
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.Inessa
F
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.

Felipafelipe answered 1/11, 2010 at 8:16 Comment(2)
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.Stare
jaxb sucks .. i could not get it work properly ... xstream works much better ... however not great at class structure changes.Desberg
P
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>
Perennate answered 8/9, 2013 at 8:12 Comment(2)
Be aware that using java.beans.XMLDecoder with user supplied data might introduce arbitrary code execution vulnerabilities in your code.Quillen
A lot of unnecessary XML is generated by XMLEncoder class. Just look at the bulky output...Menderes
C
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.

Correspondent answered 30/8, 2008 at 11:39 Comment(0)
H
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.

Harden answered 30/8, 2008 at 8:49 Comment(0)
M
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!

Meredith answered 31/8, 2008 at 11:19 Comment(1)
Problem is jaxb and xmlbeans require a mapping schema and arent auto ...Salas
M
0

Don't forget JiBX.

Metalanguage answered 29/5, 2009 at 17:2 Comment(0)
T
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.

Thagard answered 31/3, 2011 at 21:28 Comment(0)
C
-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;
}
Canal answered 24/9, 2014 at 7:59 Comment(1)
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 deserializationInessa

© 2022 - 2024 — McMap. All rights reserved.