2

I am trying to deserialize an xml file, But I am having errors on deserializing it using the code below:

try {
    Strategy strategy = new CycleStrategy("id", "ref");
    Serializer serializer = new Persister(strategy);
    File source = new File("ActionToLettersAndBorrowers.xml");
    ProcessEngineObject op = serializer.read(ProcessEngineObject.class, source);

    System.out.println(op.getName());

} catch (Exception e) {
    e.printStackTrace();
}

Am i missing something out? I got the idea from simplexml website.

ᄂ ᄀ
  • 5,669
  • 6
  • 43
  • 57
miggyyy
  • 49
  • 6
  • 2
    What are the errors that you're getting? – GBlodgett Apr 18 '18 at 12:37
  • 2
    Please, make sure that the class you are trying to deserialize has a default public constructor. – Laurent De Cant Apr 18 '18 at 12:37
  • [Related](https://stackoverflow.com/q/47407587/335858). Unfortunately, the other question has no answer, only a work-around. – Sergey Kalinichenko Apr 18 '18 at 12:39
  • @LaurentDeCant i have a constructor. public Email(String to, String from, String subject, String body) { this.to = to; this.from = from; this.subject = subject; this.body = body; } – miggyyy Apr 18 '18 at 14:54
  • @GBlodgett org.simpleframework.xml.core.PersistenceException: Constructor not matched for class nhmfc.filenet.xml.Email – miggyyy Apr 18 '18 at 14:55
  • I tried to convert the constructor into a public void method, and it works. I don't know if simplexml cannot read constructors? – miggyyy Apr 18 '18 at 15:36
  • 1
    SimpleXml like most of XML framework needs a no-arg constructor for deserialization. That was your error, and by removing your constructor, the default one was applied. Possible duplicate of [this error](https://stackoverflow.com/a/7471452/4629012) – Pagbo Apr 19 '18 at 12:23

2 Answers2

2

In Kotlin you just need to predefine your properties. Example:

@Root(name = "Response")
data class LinkResponse @JvmOverloads constructor(
@field:Element(name = "Field1")
var bucket: String = "",
@field:Element(name = "Field2")
var key: String = "",
@field:Element(name = "Field3")
var etag: String = "",
@field:Element(name = "Field4")
var location: String = ""
)
Neuron
  • 1,020
  • 2
  • 13
  • 28
0

You can define two constructors, like:

class Strategy {
...
    Strategy(){...}
    Strategy(String id, String ref){...}
}

Another approach could be defining a no-arg constructor and then set the properties you need.

marcolav
  • 405
  • 1
  • 6
  • 17