gpt4 book ai didi

java - 将xml字符串转换为java对象: getting `details` as null?

转载 作者:行者123 更新时间:2023-11-30 01:46:03 24 4
gpt4 key购买 nike

我一直在尝试将 xml 字符串转换为 Java 对象。

有一个 TV 的根标签。其中有多个字段,但我希望整个内容作为一个字符串。

@XmlRootElement(name = "TV")
@XmlAccessorType(XmlAccessType.FIELD)
public class TV {
@XmlElement
public String details;
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
@Override
public String toString() {
return "TV [details=" + details + "]";
}
}


public class XMLtoJavaObject {

public static void main(String[] args) {
String xmlString = "<TV version=\"0.91fn\"><channel><title>Friends</title><link>https://www.imdb.com/title/tt0108778/</link><season>2</season></channel></TV>";
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(TV.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
TV tv = (TV) jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
System.out.println("TV" + tv);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}

输出:

TV [details=null]

我没有将整个嵌套 xml 作为字符串。

有人可以帮我解决我所缺少的吗?

提前致谢

最佳答案

试试这个:

电视类别:

@XmlRootElement(name = "TV")
@XmlAccessorType(XmlAccessType.FIELD)
public class TV {

@XmlElement
private Channel channel;

public Channel getChannel() {
return channel;
}

public void setChannel(Channel channel) {
this.channel = channel;
}

@Override
public String toString() {
return "TV [channel=" + channel + "]";
}
}

channel 类:

@XmlAccessorType(XmlAccessType.FIELD)
public class Channel {
@XmlElement
private String title;
private String link;
private String season;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getLink() {
return link;
}

public void setLink(String link) {
this.link = link;
}

public String getSeason() {
return season;
}

public void setSeason(String season) {
this.season = season;
}

@Override
public String toString() {
return "Channel [title=" + title + ", link=" + link + ", season=" + season + "]";
}

}

输出:

TVTV [channel=Channel [title=Friends, link=https://www.imdb.com/title/tt0108778/, season=2]]

现在您可以根据需要使用 Java 获取您的详细信息,例如:

tv.getChannel().getTitle();

关于java - 将xml字符串转换为java对象: getting `details` as null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57976447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com