草庐IT

java - 简单的 XML 框架 : Having an "inline like" behaviour for objects in ElementMap

coder 2024-07-02 原文

我正在尝试在 Android 上序列化自定义对象的 Hashmap 以获得如下 xml:

<ROWSET>
   <ROW num="0">
      <Name>foo</Name>
      <FNAME>bar</FNAME>
      <BIRTH>01/01/2000</BIRTH>
      <Num>4376484</NUM>
   </ROW>
   <ROW num="1">
      <Name>bar</Name>
      <FNAME>foo</FNAME>
      <BIRTH>02/02/2000</BIRTH>
      <NUM>4376484</NUM>
   </ROW>
</ROWSET>

我创建了一个只包含我感兴趣的 Hashmap 的内部类,因为我无法按原样序列化它(并且读到这是不可能的) 添加了一个对象来测试这样 listEval.put(0,currentEvaluation) . 下面是内部类:

@Root (name="ROWSET")
public static class listOfEvals {

    @ElementMap (entry="ROW", key="num", attribute=true, inline=true)
    private Map<Integer, EvaluationContent> evalList;

    public listOfEvals(Map<Integer, EvaluationContent> list){
        evalList=list;
    }

    public Map<Integer, EvaluationContent> getEvalList() {
        return evalList;
    }

    public void setEvalList(Map<Integer, EvaluationContent> evalList) {
        this.evalList = evalList;
    }
}

EvaluationContent 对象定义如下:

public class EvaluationContent {

    @Element(name="Name", required = false)
    private String mName; 
    @Element(name="FNAME", required = false)         
    private String mFname;
    @Element(name="BIRTH", required = false)        
    private String mBirth; 
    @Element(name="Num", required = false)        
    private String mNum; 

    public String getName() {
        return mName;
    }
    public void setName(String mName) {
        this.mName = mName;
    }
     ... 
    }

问题是我得到一个 <evaluationContent>每个条目的标签:

<ROWSET>
       <ROW num="0">
          <evaluationContent>
            <Name>foo</Name>
            <FNAME>bar</FNAME>
            <BIRTH>01/01/2000</BIRTH>
            <Num>4376484</NUM>
          </evaluationContent>
       </ROW>
       <ROW num="1">
          <evaluationContent>
         ...
          <evaluationContent>
       </ROW>
    </ROWSET>

必须有更好的方法来实现,但我无法弄清楚如何,感谢您的帮助

最佳答案

我有一个解决方案——但它并不完美:

Registry registry = new Registry();

// Bind the list's class to it's converter. You also can implement it as a "normal" class.
registry.bind(EvaluationContent.ListOfEvals.class, new Converter<EvaluationContent.ListOfEvals>()
{
    @Override
    public EvaluationContent.ListOfEvals read(InputNode node) throws Exception
    {
        /* Implement if required */
        throw new UnsupportedOperationException("Not supported yet.");
    }


    @Override
    public void write(OutputNode node, EvaluationContent.ListOfEvals value) throws Exception
    {
        Iterator<Map.Entry<Integer, EvaluationContent>> itr = value.getEvalList().entrySet().iterator();

        while( itr.hasNext() )
        {
            final Entry<Integer, EvaluationContent> entry = itr.next();
            final EvaluationContent content = entry.getValue();

            // Here's the ugly part: creating the full node
            final OutputNode child = node.getChild("ROW");

            child.setAttribute("num", entry.getKey().toString());
            child.getChild("Name").setValue(content.getName());
            child.getChild("FNAME").setValue(content.getFName());
            child.getChild("BIRTH").setValue(content.getBirth());
            child.getChild("Num").setValue(content.getNum());
        }   
    }
});

Strategy strategy = new RegistryStrategy(registry);
Serializer ser = new Persister(strategy);
ser.write(list, f); // f is the Output (eg. a file) where you write to

您可以使用 @Converter() 设置转换器属性也。方法如下:

  1. 编写一个实现 Converter<EvaluationContent> 的类接口(interface),例如。 EvalListConverter
  2. 设置@Convert()列表类的属性,例如。 @Convert(value = EvalListConverter.class)
  3. 设置AnnotationStrategy坚持:Serializer ser = new Persister(new AnnotationStrategy())

另一种方法是实现一个使用 Serializer 的转换器将节点写入列表节点。 Hoewer,你真的需要玩一下。

为了测试,我已将您示例中的两个值放入列表中并对其进行序列化,生成 Xml:

<ROWSET>
   <ROW num="0">
      <Name>foo</Name>
      <FNAME>bar</FNAME>
      <BIRTH>01/01/2000</BIRTH>
      <Num>4376484</Num>
   </ROW>
   <ROW num="1">
      <Name>foo</Name>
      <FNAME>bar</FNAME>
      <BIRTH>02/02/2000</BIRTH>
      <Num>4376484</Num>
   </ROW>
</ROWSET>

文档:

关于java - 简单的 XML 框架 : Having an "inline like" behaviour for objects in ElementMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17171504/

有关java - 简单的 XML 框架 : Having an "inline like" behaviour for objects in ElementMap的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  4. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  5. 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/

  6. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  7. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  8. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  9. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  10. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

随机推荐