I Have Xml data as Follows
String Data_XML = '<?xml version="1.0" encoding=""?> <book><price>100</price><Items>2</Items> </book>';
I wanted to deserialize XML to Apex class or JSON
Class Book{
public Decimal price;
public Integer Items;
}
Best Answer
There is no quick and easy way to transform XML either into JSON or into an Apex Class.
I came up against this in a recent project, and I ended up using the Dom.Document and Dom.XmlNode classes.
There's likely a way to abstract this pattern, but the basic idea that I used was to have an outer class to start the parsing, and then have a bunch of inner classes to represent the structure of the XML. It's effectively an implementation of a depth-first search algorithm
In your provided case, the solution is on the simple side
In general, each inner class that represents part of the XML data structure implements a
process(Dom.XmlNode)
method. The strengths of this pattern are that it limits the complexity of theprocess()
method for each class, it doesn't care what order child nodes appear in, and it can parse the entire structure with a single call (here, it would beBookParser bp = new BookParser(inputXML);
.