代码之家  ›  专栏  ›  技术社区  ›  Sach

Jackson将XML属性转换为平面JSON

  •  0
  • Sach  · 技术社区  · 6 年前

    我有这个(模拟实际生产数据)XML,需要按如下方式转换成JSON(我使用的是jackson2.8):

    <testCode code="ABC" lang="java" />
    

    我对这件事的看法如下:

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "Phone", propOrder = {
      "descriptions"
    }
    @XmlRootElement(name="phone")
    public class Phone extends PhoneBase {
    
    protected TestCode testCode;
    
    getter()
    setter();
    }
    

    测试代码如下:

    XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "TestCode", propOrder = {
    "code"
    })
    public class TestCode {
    
    protected String descriptor;
    
    @XmlAttribute(required = true)       
    protected String code;
    
    @XmlAttribute   
    protected String lang;
    }
    

    在将其转换为JSON时,我得到以下信息:

     testCode: {
     code: "ABC",
     lang: "java"
     }
    

    当我想要如下的东西时:

    testCode: "ABC"
    

    请注意,我忽略了任何其他属性并扁平化了“代码”。另外,不需要“编码”自己。

    有人能推荐一个指针吗?我尝试了xmlementwrapper,但它不起作用。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Sach    6 年前

       @JsonValue
       public String toJson() {
             return this.code;
       }