草庐IT

java - JAXB:根据元素值解码到子类

coder 2024-06-27 原文

我正在尝试使用包含项目列表的 JAXB 解析 XML 文件。项目的类别取决于 XML 中元素的值。

这是一个遗留系统,我无法轻易更改输入格式。

例如,给定以下 XML 和类定义:

<root>
    <type>a</type>
    <item>
       <a>a1</a>
    </item>
    <item>
       <a>a2</a>
    </item>
</root>

@XmlRootElement(name = "root")
public class Root {
    @XmlElement
    String type;

    @XmlElement(name="item")
    List<Item> items;
}

public class Item {}
public class ItemA extends Item {
    @XmlElement
    String a;
}
public class ItemB extends Item {
    @XmlElement
    String b;
}

现在,items 列表包含两个 Item 对象。

我需要生成的 Root 对象中的项目列表包含两个 ItemA 对象,一个带有 a="a1",另一个带有 a="a2"。

如果类型元素是“b”,我需要项目列表包含 ItemB 对象。

在单个 XML 文件中只能指定一个类型元素。

我见过几个使用属性值的解决方案,但没有一个使用元素值。

最佳答案

遵循 Blaise Doughan 的提示您可以创建一个 XmlAdapter。不幸的是,适配器在根级别不可用,因此您必须在取消/编码期间添加一些额外的代码。

Root/Item/ItemA/ItemB 是普通的 POJO,此处没有任何注释。

具有适配类型的适配器:

public class RootAdapter extends XmlAdapter<AdaptedRoot, Root>
{
    @Override
    public Root unmarshal( AdaptedRoot v ) throws Exception
    {
        Root root = new Root();
        root.type = v.type;
        for ( AdaptedItem adaptedItem : v.items )
        {
            if ( v.type.equals( "a" ) )
            {
                ItemA a = new ItemA();
                a.a = adaptedItem.a;
                root.items.add( a );
            }
            if ( v.type.equals( "b" ) )
            {
                ItemB b = new ItemB();
                b.b = adaptedItem.b;
                root.items.add( b );
            }
        }
        return root;
    }

    @Override
    public AdaptedRoot marshal( Root v ) throws Exception
    {
        AdaptedRoot adapted = new AdaptedRoot();
        adapted.type = v.type;
        for ( Item item : v.items )
        {
            AdaptedItem adaptedItem = new AdaptedItem();
            if ( v.type.equals( "a" ) )
            {
                adaptedItem.a = ((ItemA) item).a;
            }
            if ( v.type.equals( "b" ) )
            {
                adaptedItem.b = ((ItemB) item).b;
            }
            adapted.items.add( adaptedItem );
        }
        return adapted;
    }

    @XmlRootElement( name = "root" )
    public static class AdaptedRoot
    {
        @XmlElement
        String            type;
        @XmlElement( name = "item" )
        List<AdaptedItem> items = new ArrayList<>();
    }

    public static class AdaptedItem
    {
        @XmlElement
        String a;
        @XmlElement
        String b;
    }
}

Un-/marshalling 可以像这样完成:

public static void main( String[] args ) throws Exception
{
    String rawRootA = "<root><type>a</type><item><a>a1</a></item><item><a>a2</a></item></root>";
    String rawRootB = "<root><type>b</type><item><b>b1</b></item><item><b>b2</b></item></root>";

    Root rootA = unmarshal( rawRootA );
    for ( Item item : rootA.items )
    {
        System.out.println( item.getClass().getSimpleName() );
    }
    print( rootA );

    Root rootB = unmarshal( rawRootB );
    for ( Item item : rootB.items )
    {
        System.out.println( item.getClass().getSimpleName() );
    }
    print( rootB );
}

public static Root unmarshal( String xml ) throws Exception
{
    JAXBContext context = JAXBContext.newInstance( AdaptedRoot.class );
    Unmarshaller unmarshaller = context.createUnmarshaller();
    XmlAdapter<AdaptedRoot, Root> adapter = new RootAdapter();

    AdaptedRoot adapted = (AdaptedRoot) unmarshaller.unmarshal( new StringReader( xml ) );
    return adapter.unmarshal( adapted );
}

public static void print( Root root ) throws Exception
{
    JAXBContext context = JAXBContext.newInstance( AdaptedRoot.class );
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
    XmlAdapter<AdaptedRoot, Root> adapter = new RootAdapter();

    AdaptedRoot adaptedRoot = adapter.marshal( root );
    marshaller.marshal( adaptedRoot, System.out );
}

预期输出:

ItemA
ItemA
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <type>a</type>
    <item>
        <a>a1</a>
    </item>
    <item>
        <a>a2</a>
    </item>
</root>
ItemB
ItemB
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <type>b</type>
    <item>
        <b>b1</b>
    </item>
    <item>
        <b>b2</b>
    </item>
</root>

关于java - JAXB:根据元素值解码到子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20797405/

有关java - JAXB:根据元素值解码到子类的更多相关文章

  1. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  2. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  3. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  4. Ruby——嵌套类和子类是一回事吗? - 2

    下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby​​解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc

  5. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  6. ruby - 在哈希的键数组中追加元素 - 2

    查看我的Ruby代码:h=Hash.new([])h[0]=:word1h[1]=h[1]输出是:Hash={0=>:word1,1=>[:word2,:word3],2=>[:word2,:word3]}我希望有Hash={0=>:word1,1=>[:word2],2=>[:word3]}为什么要附加第二个哈希元素(数组)?如何将新数组元素附加到第三个哈希元素? 最佳答案 如果您提供单个值作为Hash.new的参数(例如Hash.new([]),完全相同的对象将用作每个缺失键的默认值。这就是您所拥有的,那是你不想要的。您可以改用

  7. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  8. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  9. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

  10. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

随机推荐