我有一个有日文字符的xml。 Xml正在被正确编组,但是哪个jaxbUnmarshalling所有字符都被转换为'?' 请在下面找到代码: -
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
String name;
int age;
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;
}
}
JAXBExample
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
public static void main(String[] args) {
Customer customer = new Customer();
customer.setId(100);
customer.setName("株式会社三菱東京UFJ銀行");
customer.setAge(29);
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING,"UTF-8");
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Conversion.java
public class Conversion {
public static void main(String[] args) {
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer.getName());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
OutPUT: -
XML: -
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
<age>29</age>
<name>株式会社三菱東京UFJ銀行</name>
</customer>
运行Conversion.java类后,我得到以下输出: -
客户名称?UFJ ??
请帮助我搜索网但找不到任何解决方案。
答案 0 :(得分:0)
尝试使用正确的编码自行构建Reader
并将Reader
提供给Unmarshaller#unmarshal()
,而不是File
:
File file = new File("C:\\file.xml");
try (Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8")) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(reader);
System.out.println(customer.getName());
} catch (JAXBException e) {
e.printStackTrace();
}
}
此外,如果您的平台编码类似于latin1
,那么System.out
会使用它并破坏正在输出的数据(将其替换为问号)。请运行您的程序:
java -Dfile.encoding=utf-8 JAXBExample
顺便说一下,如果没有Reader
相关的扭曲,这可能就足以解决问题,因为unmarshal()
方法应该尊重XML文件中指定的编码。