java - 将 POJO 打印到 System.out 问题

标签 java jaxb

按照一些教程 (this one),我在控制台上没有得到相同的输出。 本教程介绍如何使用 JAXB API - JAXBContext、Unmarshaller、Marshaller 将 Java 对象与 XML 相互转换。

这是 POJO 代码:

package com.jaxb.example;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    private String name;
    private int age;
    private int id;

    public String getName() {
        return name;
    }
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }
    public int getId() {
        return id;
    }
    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}

这是解码代码:

package com.jaxb.example;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBExampleTestUnmarshall {

    public static void main(String [] args){

        try {
            File file = new File("./jaxb-data/file.xml");

            JAXBContext context = JAXBContext.newInstance(Customer.class);
            Unmarshaller jaxbUnmarshaller = context.createUnmarshaller();

            Customer customer = (Customer)jaxbUnmarshaller.unmarshal(file);
            //System.out.println(customer.getId());
            //System.out.println(customer.getName());
            //System.out.println(customer.getAge());
            System.out.println(customer);

        } catch (JAXBException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

}

这是./jaxb-data/file.xml文件内容:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="1">
    <age>33</age>
    <name>Some Name</name>
</customer>

当我运行这个类时,我得到 com.jaxb.example.Customer@15e8d410

问题:为什么我在输出中没有得到 Customer [name=Some Name, age=33, id=1]

最佳答案

您必须覆盖 Customer#toString,当您 Sysout 一个对象时它会被隐式调用。标准实现是该对象的完全限定类名和十六进制编码的hashcode()

关于java - 将 POJO 打印到 System.out 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23759914/

相关文章:

java - 如何在 Hibernate Java obj 中添加 @XmlTransient

java - 仅打印工作日

java - 处理 JAXB 中的嵌套元素

java - XJC NullPointerException 仅在 Java > 7u40 中

java - 当使用系统属性定义资源时,获取 SQLException : Driver:org. hsqldb.jdbcDriver 在 tomee 中为 URL 返回 null

java - 使用命名空间生成的 Jaxb cxf-xjc 插件

java - 符号已定义。使用 JAXB 属性解决冲突

java - Spring Boot 中的 CORS 不起作用 - 得到空响应

java - 我想在新框架窗口出现时隐藏第一帧

java - 从客户适配器的 getView 中的 onclick 监听器访问特定 View