Dmitry
Dmitry

Reputation: 369

Simple Library Xml serialization without new instance of class

In my Java project I try to use Simple Library (http://simple.sourceforge.net) for XML serialization. Now I need do serializing from xml into existing instance of my class. but this library always create new instance. For example I have some object in memory:

TObj myObject = new TObj();
myObject.field1 = 999;
myObject.field2 = 777;

Then I receive from server xml of this TObj but only part of fields, such as:

 <TObj field1="100">

I want serialize this xml in myObject variable. and after that result should be:

myObject.field1 = 100;
myObject.field2 = 777;

But simple library always create new instance of TObj class. How I can achieve the desired???

Thanks

Upvotes: 0

Views: 333

Answers (2)

Wang Zhong
Wang Zhong

Reputation: 190

maybe your TObj class doesn't follow simplexml's serialization & deserialization rules correctly.

I recommend you to use annotations to define your TObj so that simplexml will know how to serialize your object. Here is an example:

@Root(name = "Example")
public class SimpleExample {
    @Element(name = "Name", required = false)
    private String name;
}

By doing this, you can create a new instance of class SimpleExample and serialize it with the following method:

    public static <T> String marshal(T obj, Class<T> clazz) throws Exception {
    Strategy strategy = new AnnotationStrategy();
    Serializer serializer = new Persister(strategy, format);
    StringWriter out = new StringWriter();
    serializer.write(obj, out);
    return out.toString();
}

You will get something like:

<?xml version="1.0" ?>
<Example>
    <Name>value_of_this_field<Name>
<Example>

Upvotes: 0

Billy Bob Bain
Billy Bob Bain

Reputation: 2895

Use the read() method on Serializer that accepts an instance of your class instead of the .class.

http://simple.sourceforge.net/download/stream/doc/javadoc/org/simpleframework/xml/Serializer.html#read(T, java.io.File)

Upvotes: 3

Related Questions