【问题标题】:Need the proper object declaration for my XStream deserialization我的 XStream 反序列化需要正确的对象声明
【发布时间】:2012-10-13 23:24:35
【问题描述】:

我的 XML:

<autocomplete>
  <url_template>http://api-public.netflix.com/catalog/titles/autocomplete?{-join|&amp;|term}</url_template>
  <autocomplete_item>
    <title short="Star Wars: Episode V: The Empire Strikes Back: Original Theatrical Version"></title>
  </autocomplete_item>
</autocomplete>

我的对象:

public class AutoCompleteList
{
public String url_template;
public List<AutocompleteItem> autocomplete_item;
}

public class AutocompleteItem
{
public Title title;
}

public class Title
{
@XStreamAlias("short")
public String Short;
}

我的代码:

XStream xstream = new XStream();
xstream.alias("autocomplete", AutoCompleteList.class);
xstream.alias("title", Title.class);
AutoCompleteList myObj = (AutoCompleteList)xstream.fromXML(stringFromStream);

我无法从 XML 中检索“短标题”值。

另外,如果我的 XML 包含一组以上的 autocomplete_item 标记,xstream 会报错并抱怨存在重复的 autocomplete_item 实例。

有什么建议吗?

我在这里搜索了很多问题,但似乎没有任何对我有用。

【问题讨论】:

    标签: java xml object xstream


    【解决方案1】:

    对于short 属性,尝试添加@XStreamAsAttribute 注释:

    public class Title
    {
      @XStreamAlias("short")
      @XStreamAsAttribute
      public String Short;
    }
    

    并在致电fromXML 之前致电xstream.processAnnotations(Title.class)

    对于多个autocomplete_item 问题,您应该使用@XStreamImplicit

    public class AutoCompleteList
    {
      public String url_template;
    
      @XStreamImplicit(itemFieldName="autocomplete_item")
      public List<AutocompleteItem> autocomplete_item;
    }
    

    同样,您需要先调用 xstream.processAnnotations(AutoCompleteList.class) 告诉 XStream 读取注释,然后才能调用 fromXML

    【讨论】:

    • 这正是我所需要的。谢谢你。这让我发疯了。
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2015-03-26
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多