There is XML with this structure:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> <object type="People"> <field id="name" type="class java.lang.String" value="Ivan"/> <field id="age" type="class java.lang.Integer" value="23"/> <field id="salary" type="double" value="50.0"/> </object> 

But the type of the object and the field may differ. For example, the file might be:

 <object type="Worker"> <field id="lastName" type="class java.lang.String" value="Ivan"/> <field id="height" type="double" value="170.00"/> <field id="salary" type="double" value="50.0"/> </object> 

Is it possible to create an object from a similar document?

  • one
    XML -> Json -> Gson (ta-daam) - Flippy
  • An interesting task, plus. Let's ponder. As I understand it, your file should turn into a class with some variables. Use reflection, to be honest, the option is not very. You can create one class and make a collection. As for the class name, you can save the value of <object type="тут" as a regular string. Now the variables themselves are with data. You can rip a java.lang.String type string and create a class from it via Class.forName() - Flippy
  • But! You cannot predict which type will be used. How many maximum variables can there be? Okay, 5. Ah, let's say types 3 - int , double , String . We take each type as a string and check it with "hands". If java.lang.String , then take the value and shove it into a variable, calling it in advance like in the file - Flippy
  • Ugh, that's impossible. Author, you definitely need to name the class and variables as in the file. Who is my first comment? I didn’t write it seriously.)) - Flippy

1 answer 1

  1. Yes you can. Look in the direction of generating bytecode. For example: cglib
  2. You do not need it. Take advantage of serialization.

    1. Jackson
    2. Gson
  • Jackson for parsing xml in json , and gson for parsing json in pojo ? I'm right? - Flippy
  • @Flippy, Jackson can xml <-> pojo and json <-> pojo. And gson to work with json as an alternative. - Victor Khovanskiy
  • Thank. I will know :) - Flippy