user82334
user82334

Reputation: 279

How to deserialize xml data from c# to java?

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">
    <MyText>Blah Blah</MyText>
    <Flag>false</Flag>
</Sample>

Upvotes: 2

Views: 2932

Answers (4)

oo_olo_oo
oo_olo_oo

Reputation: 2825

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

Upvotes: 1

serg10
serg10

Reputation: 32667

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.

Upvotes: 1

David Robbins
David Robbins

Reputation: 10046

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.

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272217

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.

Upvotes: 1

Related Questions