简体   繁体   中英

How to deserialize xml data from c# to java?

I have identical objects in both ac# 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>

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.

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.

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 .

用作Java反序列化解决方案的简单库看起来很有希望。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM