How can I get the values of the nested objects in XStream?

别等时光非礼了梦想. 提交于 2019-12-12 01:12:32

问题


I have a class of user with the following attributes:

/** The username. */
private String username;
/** The password. */
private String password;
/** The list of role names the user has. */
private List<String> roleNames;
/** The list of partners with the associated database */
private DbPartner dbPartner;
/** The list of message types with the associated database */
private DbMessageType dbMessageType;

I use XStream to write values in a file and get them from it. The problem is that the values of the nested objects (dbPartner and dbMessageTypes) are not filled and they are null when I get user from xml. What should I do?

This is the method that I use to get data from the file:

 private void lazyLoad() {
    synchronized (ConfigurationDAOImpl.class) {
        // Has the configuration been loaded
        if (configuration == null) {
            if (filename.exists()) {
                try {
                    XStream xStream = new XStream(new DomDriver());
                    xStream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);

                    xStream.alias("configuration", Configuration.class);
                    xStream.alias("user", User.class);
                    xStream.alias("dbPartner", DbPartner.class);
                    xStream.alias("dbMessageType", DbMessageType.class);

                    configuration = (Configuration) xStream
                            .fromXML(filename.getInputStream());

                    LOGGER.debug("Loaded configuration from {}.", filename);
                } catch (Exception e) {
                    LOGGER.error("Failed to load configuration.", e);
                }
            } else {
                LOGGER.debug("{} does not exist.", filename);
                LOGGER.debug("Creating blank configuration.");

                configuration = new Configuration();
                configuration.setUsers(new ArrayList<User>());

                // and store it
                store();
            }
        }
    }
}

private void store() {
    XStream xStream = new XStream();
    xStream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);

    xStream.alias("configuration", Configuration.class);
    xStream.alias("user", User.class);
    xStream.alias("dbPartner", DbPartner.class);
    xStream.alias("dbMessageType", DbMessageType.class);

    synchronized (ConfigurationDAOImpl.class) {
        try {
            xStream.toXML(configuration, new FileOutputStream(filename.getFile()));
        } catch (IOException e) {
            throw new RuntimeException("Failed to write to " + filename, e);
        }
    }
}

来源:https://stackoverflow.com/questions/7983333/how-can-i-get-the-values-of-the-nested-objects-in-xstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!