javaxmlswingxstream

converting xml file into Object using xstream but if a Variable not present in xml file but in Object then it assign default value to it how to change


this is xml file

<com.baeldung.pojo.Customer>
    <firstName>John</firstName>
    <lastName>Doe</lastName>
    <dob>1986-02-14 03:46:16.381 UTC</dob>
</com.baeldung.pojo.Customer>

this is java object

public class Customer {
 
    private String firstName;
    private String lastName;
    private Date dob;
    private isMale;
 
    // standard setters and getters
}

isMale not in xml file so when i convert xml file into Customer Object it assign isMale=false but i want it to assign it true by default only for once

conversion code

public static <A> A fromXML(Class<A> c, File file) {
            
            XStream xStream = new XStream();
            // Avoid "Security framework of XStream not initialized, XStream is probably vulnerable." warning.
            XStream.setupDefaultSecurity(xStream);
            xStream.allowTypesByWildcard(new String[] {
                    "configurationFiles.**",
                    "java.awt.Dimension"
            });
            xStream.ignoreUnknownElements();
    
            InputStream inputStream = null;
            Reader reader = null;
    
            try {
                inputStream = new java.io.FileInputStream(file);
                //System.out.println("inside fromXml  try");
                reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
                Object object = xStream.fromXML(reader);
                
                
    //          boolean isMarriedExists = ((Object) xStream).getUnmarshaller().getContext().hasField("isMarried");
    
                // System.out.println(c+"--"+object);
                if (c.isInstance(object)) {
    
                    return (A)object;
                }
            } 
            catch (Exception exp) {
                //System.out.println("inside fromXml  catch");
                exp.printStackTrace();
                //log.error(null, exp);
            } catch (java.lang.Error err) {
                //System.out.println("inside fromXml  catch");
                err.printStackTrace();
                //log.error(null, err);
            } finally {
                close(reader);
                close(inputStream);
            }
    
            
            return null;
        }

using above mention function and converting the xml file using xStream.

File f = new File("customer.xml");
        MainFrameXmlOptions mainFrameOptions=null;
        if(f.exists())
            mainFrameOptions = fromXML(MainFrameXmlOptions.class, f);

Solution

  • Try adding ctor

    public Customer() {
      super();
      isMale = true;
    }
    

    You will need to get XStream to honour that with

    XStream xStream = new XStream(new com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider());