views:

591

answers:

4

I have identical objects in both a c# server app and a java client app. The server XML serializes these objects and makes them available through a REST service. The java app downloads the data in XML format. What is the best way to deserialize the xml data to my java objects? I am currently using Java org.w3c.dom classes to parse the xml and create new objects. I understand that certain types like dates and byte arrays will have to be handled manually, but a point in the right direction would be appreciated.

C# Class:

public class Sample {
    public string MyText { get; set; }
    public bool Flag { get; set; }
    //many more fields
}

Java Class:

public class Sample {
    public String MyText;
    public boolean Flag;
}

Here is the xml thats coming from the c# web app:

<?xml version="1.0" encoding="utf-8"?>
<Sample xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
    <MyText>Blah Blah</MyText>
    <Flag>false</Flag>
</Sample>
A: 

One possible approach on the Java end is to use XStream. It offers a trivial means of deserialising XML to Java objects, without requiring a schema definition.

XStream will normally expect Java class/package names as XML elements. However you can modify this behaviour through the use of aliases. Given the above requirements you'll need this facility. See this tutorial for more information.

Brian Agnew
A: 

Why not serialize to JSON in C# then deserialize in Java. Both platforms have JSON support / libraries. From the C# side you can use JSON.Net. JSON will produce a light-weight file much smaller than XML and should be a bit faster when processing.

David Robbins
I would like to use this approach, however existing systems are already using this data format.
+1  A: 

JAXB is a way of binding an xml schema to Java classes. You can even generate your classes from a schema or dtd. Or you can manually annotate your java classes with xpath like expressions that tell JAXB how to deserialize XML.

If that is a little heavyweight then Java offers many choices of how to read xml from a file. I like commons digester, and Sun's newish streaming api for xml.

serg10
A: 

Simple library, used as Java deserialization solution, looks quite promising.

oo_olo_oo