我正在使用Jackson将JSON文件转换为ArrayList,然后转换为XML。它显示在Firefox中,但就像普通字符串一样。通过使用inspect元素工具,我获得了整个格式化的xml。我可以使用哪个功能在浏览器上正确显示?
我的方法:
private void init() throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
InputStream is = MyClass[].class.getResourceAsStream("/config/myList.json");
myList= Arrays.asList(mapper.readValue(is, MyClass[].class));
XmlMapper xmlMapper = new XmlMapper();
for(MyClass test : myList){
String asXml += xmlMapper.writeValueAsString(test);
}
LOGGER.info("asXml: {}.", asXml);
}
浏览器中的所需输出:
<myclass xmlns="">
<myclass>XyClass</ci>
<myname>XyName</ci>
...
</myclass>
实际输出: XyClassXyName ...
相当简化的课程如下:
@JacksonXmlRootElement(localName ="MyClass")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyClass {
@XmlElement(required = true)
private String class;
@XmlElement(required = true)
private String name;
//....
//standard constructor
public MyClass() { }
public CI(String class, String name){
this.class = class;
this.name = name;
}
public String getClass() {
return class;
}
public String getName() {
return name;
}
public void setClass(String class) {
this.class = class;
}
public void setName(String name) {
this.name = name;
}
}
另一个奇怪的事情是我在另一个类中有确切的注释,尝试相同的东西,浏览器没有显示任何东西......感谢任何帮助。
答案 0 :(得分:0)
我的错误基本上来自两件事。最重要的是XML根元素的定义(不仅仅是“MyClass”中的注释)。定义一个全局字符串来创建一个XML Root元素,否则你的文档将不会格式正确,并且将显示“文件元素之后的垃圾”错误。
private String asXml ="<?xml version=\"1.0\" encoding=\"utf-8\"?><MyList>";
我已经将方法改编为:
private void init() throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
InputStream is = MyClass[].class.getResourceAsStream("/config/myList.json");
myList= Arrays.asList(mapper.readValue(is, MyClass[].class));
XmlMapper xmlMapper = new XmlMapper();
for(MyClass test : myList){
String asXml += xmlMapper.writer().with(SerializationFeature.WRAP_ROOT_VALUE).withRootName("MyClass").writeValueAsString(test);
}
LOGGER.info("asXml: {}.", asXml);
asXml += "</MyList>";
}
不要忘记在RestController中添加正确的MediaType:
@RequestMapping(value="/display", method=RequestMethod.GET, produces=MediaType.APPLICATION_XML_VALUE)
public @ResponseBody String getList(Model model) {
return service.getAsXmlString();
}