GVKun编程网logo

使用JAXB解组/编组List (cjson解析数组)

4

想了解使用JAXB解组/编组List的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于cjson解析数组的相关问题,此外,我们还将为您介绍关于javaJAXB如何处理List>、JavaLis

想了解使用JAXB解组/编组List 的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于cjson解析数组的相关问题,此外,我们还将为您介绍关于java JAXB 如何处理 List>、Java List list=new ArrayList();为什么要声明为List,而不是ArrayList、java – JAXB解组树结构、java – 使用JAXB解组嵌套的xml项列表的新知识。

本文目录一览:

使用JAXB解组/编组List <String>(cjson解析数组)

使用JAXB解组/编组List (cjson解析数组)

我正在尝试创建一个非常简单的REST服务器。我只是有一个测试方法,它将返回字符串列表。这是代码:

@GET@Path("/test2")public List test2(){    List list=new Vector();    list.add("a");    list.add("b");    return list;}

它给出以下错误:

严重:Java类型的消息正文编写器,类java.util.Vector和MIME媒体类型,找不到应用程序/八位位组流

我希望JAXB对诸如String,Integer等简单类型具有默认设置。我想不是。这是我的想象:

<Strings>  <String>a</String>  <String>b</String></Strings>

使这种方法最简单的方法是什么?

答案1

小编典典

我使用@LiorH的示例并将其扩展为:

@XmlRootElement(name="List")public class JaxbList<T>{    protected List<T> list;    public JaxbList(){}    public JaxbList(List<T> list){        this.list=list;    }    @XmlElement(name="Item")    public List<T> getList(){        return list;    }}

注意,它使用泛型,因此您可以将其与String之外的其他类一起使用。现在,应用程序代码很简单:

    @GET    @Path("/test2")    public JaxbList test2(){        List list=new Vector();        list.add("a");        list.add("b");        return new JaxbList(list);    }

为什么JAXB包中不存在这个简单的类?有人在其他地方看到类似的东西吗?

java JAXB 如何处理 List<Map<String, String>>

java JAXB 如何处理 List>

entity 如下:

public class User {
	private int count;
	private List<Map<String, String>> rows;
        
}

通过 JAXB 如何序列化成以下格式

<user>
	<count></count>
	<rows>
		<row>
			<id></id>
			<name></name>
		</row>
		<row>
			<id></id>
			<name></name>
		</row>
	</rows>
<user>

其中 id、name 为 Map 中的 Key,主要是这里的 Map 如何才能序列化这种格式

望各位不吝赐教,谢过



Java List<String> list=new ArrayList<String>();为什么要声明为List,而不是ArrayList<String>

Java List list=new ArrayList();为什么要声明为List,而不是ArrayList

例如:代码List list = new ArrayList();

下面通过list来操作集合。假如代码编写后却发现集合使用的不准确,应该使用LinkedList,那么只要修改一行代码List list = new LinkedList();就可以。

这行以后的代码不需要修改,因为List接口保证了调用的都是接口中的方法,而ArrayListLinkedList都实现了List接口。

而如果当时用ArrayList list = new ArrayList()这种形式的话,那么list访问到的就可能是ArrayList里独有的方法而非List接口中的方法。这样替换成LinkedList的时候就有可能需要修改很多的代码。

java – JAXB解组树结构

java – JAXB解组树结构

我有 XML输入,它本质上是一个树结构.目标是(un)将代码编组到 Java类中.

<config>

<key-value-pair>
   <key>Key1</key>
   <value>Value1</value>
</key-value-pair>

<key-value-pair>
   <key>Key2</key>
   <value>
      <key-value-pair>
         <key>Subkey2</key>
         <value>Value999</value>
      </key-value-pair>
   </value>
</key-value-pair>

</config>

XML包含典型的键/值对.并且每个值可以包含另一个键/值对,或列表键/值对或仅包含单个字符串值.

@XmlRootElement
@XmlAccessorType(XmlAccesstype.FIELD)
static class keyvaluePair {

    @XmlElement(name="key")
    private String key;

    @XmlElement(name="value")
    private String value;   // here I don't kNow how to reflect
                            // the choice of String or another
                            // list of keyvaluePair objects
    @XmlElement(name="value")
    private List<keyvaluePair> valuePairs;

    // getters/setters here
}

然后我只有另一个包装类

@XmlRootElement(name="config")
@XmlAccessorType(XmlAccesstype.FIELD)
static class Structure {

    @XmlElement(name="key-value-pair")
    private List<keyvaluePair> keyvaluePair;

    // getters/setters
 }

这是我试图用于(联合国)编组的逻辑.

Unmarshaller jaxbUnmarshaller = jc.createUnmarshaller();
 StringReader reader = new StringReader(input);
 Structure struct = (Structure) jaxbUnmarshaller.unmarshal(reader);
 // struct doesn't get the data correctly ...

这是我到目前为止所得到的.它不像我拥有的​​那样工作,但我希望我能清楚自己最终目标应该是什么样子.

我想在开始时使用XML并放入Structure类的实例.

解决方法

你可能已经想到了这个……
如果你开始在这样的模式级别建模它;

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="key-value-pair">
    <xs:sequence>
     <xs:element name="key" type="xs:string"/>
     <xs:element name="value">
        <xs:complexType mixed="true">
            <xs:choice>
                <xs:element name="key-value-pair" type="key-value-pair" minOccurs="0"/>
            </xs:choice>
        </xs:complexType>
     </xs:element>
    </xs:sequence>
  </xs:complexType>
  <xs:element name="config">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="key-value-pair" type="key-value-pair" minOccurs="1" maxOccurs="unbounded"/>
        </xs:sequence>  
    </xs:complexType>
  </xs:element>
</xs:schema>

然后使用XJC Ant Task或call it programmatically或其他任何内容来生成最终的JAXB类

package uk.co.his.test.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccesstype;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for key-value-pair complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType name="key-value-pair"&gt;
 *   &lt;complexContent&gt;
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
 *       &lt;sequence&gt;
 *         &lt;element name="key" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
 *         &lt;element name="value"&gt;
 *           &lt;complexType&gt;
 *             &lt;complexContent&gt;
 *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
 *                 &lt;choice&gt;
 *                   &lt;element name="key-value-pair" type="{}key-value-pair" minOccurs="0"/&gt;
 *                 &lt;/choice&gt;
 *               &lt;/restriction&gt;
 *             &lt;/complexContent&gt;
 *           &lt;/complexType&gt;
 *         &lt;/element&gt;
 *       &lt;/sequence&gt;
 *     &lt;/restriction&gt;
 *   &lt;/complexContent&gt;
 * &lt;/complexType&gt;
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccesstype.FIELD)
@XmlType(name = "key-value-pair",propOrder = {
    "key","value"
})
public class keyvaluePair {

    @XmlElement(required = true)
    protected String key;
    @XmlElement(required = true)
    protected keyvaluePair.Value value;

    /**
     * Gets the value of the key property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getKey() {
        return key;
    }

    /**
     * Sets the value of the key property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setKey(String value) {
        this.key = value;
    }

    /**
     * Gets the value of the value property.
     * 
     * @return
     *     possible object is
     *     {@link keyvaluePair.Value }
     *     
     */
    public keyvaluePair.Value getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     * 
     * @param value
     *     allowed object is
     *     {@link keyvaluePair.Value }
     *     
     */
    public void setValue(keyvaluePair.Value value) {
        this.value = value;
    }


    /**
     * <p>Java class for anonymous complex type.
     * 
     * <p>The following schema fragment specifies the expected content contained within this class.
     * 
     * <pre>
     * &lt;complexType&gt;
     *   &lt;complexContent&gt;
     *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
     *       &lt;choice&gt;
     *         &lt;element name="key-value-pair" type="{}key-value-pair" minOccurs="0"/&gt;
     *       &lt;/choice&gt;
     *     &lt;/restriction&gt;
     *   &lt;/complexContent&gt;
     * &lt;/complexType&gt;
     * </pre>
     * 
     * 
     */
    @XmlAccessorType(XmlAccesstype.FIELD)
    @XmlType(name = "",propOrder = {
        "content"
    })
    public static class Value {
        @XmlElementRef(name = "key-value-pair",type = JAXBElement.class,required = false)
        @XmlMixed
        protected List<Serializable> content;

        /**
         * Gets the value of the content property.
         * 
         * <p>
         * This accessor method returns a reference to the live list,* not a snapshot. Therefore any modification you make to the
         * returned list will be present inside the JAXB object.
         * This is why there is not a <CODE>set</CODE> method for the content property.
         * 
         * <p>
         * For example,to add a new item,do as follows:
         * <pre>
         *    getContent().add(newItem);
         * </pre>
         * 
         * 
         * <p>
         * Objects of the following type(s) are allowed in the list
         * {@link String }
         * {@link JAXBElement }{@code <}{@link keyvaluePair }{@code >}
         * 
         * 
         */
        public List<Serializable> getContent() {
            if (content == null) {
                content = new ArrayList<Serializable>();
            }
            return this.content;
        }

    }

}

还有一个ObjectFactory和一个Config类(基本上就是你的Structure类). ObjectFactory给了我们一些’糖’来帮助可怕的JAXBElement舞蹈.

正如安德烈亚斯所说,仍将允许String和嵌套的keyvaluePair(s).然后,您必须使用验证器包装Config类以检查未发生的情况;例如;

package uk.co.his.test;

import java.io.Serializable;
import java.util.List;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;

import uk.co.his.test.model.Config;
import uk.co.his.test.model.keyvaluePair;

public class Validate {


    public void validate(Config c) throws JAXBException
    {
        for(keyvaluePair kvp: c.getkeyvaluePair())
        {
            validate(kvp);  
        }
    }

    public void validate(keyvaluePair kv) throws JAXBException
    {
        List<Serializable> mixed = kv.getValue().getContent();
        boolean nonWhitespaceStringFound = false;
        boolean kvpFound = false;
        for(Serializable c: mixed)
        {
            if(c instanceof String)
            {
                String s  = (String) c;
                if(s.trim().length()>0) {
                    nonWhitespaceStringFound = true;
                }
            }
            else
            {
                @SuppressWarnings("unchecked")
                JAXBElement<keyvaluePair> t = (JAXBElement<keyvaluePair>) c;
                keyvaluePair child = t.getValue();
                kvpFound = true;
                validate(child);
            }
            if(kvpFound && nonWhitespaceStringFound) {
                throw new JAXBException("keyvaluePair "+kv.getKey()+" value element contained String data and nested keyvaluePair(s)");
            }
        }
    }
}

要创建配置,您必须进行JAXBElement舞蹈;

private static final File Test1Out = new File("files/test1.xml");
@Test
public void test1() throws JAXBException
{
    ObjectFactory of = new ObjectFactory();
    Config c = new Config();
    c.getkeyvaluePair().add(createKVPair(of,2,"a","one"));
    c.getkeyvaluePair().add(createKVPair(of,1,"b","two"));
    c.getkeyvaluePair().add(createKVPair(of,"c","three"));
    JAXBContext jbc = JAXBContext.newInstance("uk.co.his.test.model");
    Marshaller m = jbc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
    m.marshal(c,Test1Out);

    Unmarshaller u = jbc.createUnmarshaller();
    Config c2 = (Config) u.unmarshal(Test1Out);
    Assert.assertTrue("Round trip produces different things",c2.getkeyvaluePair().size() ==3);
}

private keyvaluePair createKVPair(ObjectFactory of,int depth,int length,String initialKey,String value) {
    keyvaluePair kv = new keyvaluePair();
    kv.setKey(initialKey);
    Value v = new Value();
    kv.setValue(v);
    if(depth==0)
    {
        v.getContent().add(value);
    }
    else 
    {
        int newdepth = --depth;
        for(int i = 0; i < length; i++)
        {
            v.getContent().add(of.createkeyvaluePairValuekeyvaluePair(createKVPair(of,newdepth,length,initialKey+depth,value+i)));
        }
    }
    return kv;
}

嗯,这是一个开始……

java – 使用JAXB解组嵌套的xml项列表

java – 使用JAXB解组嵌套的xml项列表

我有这样的xml结构,我需要使用JAXB转换为 java对象:

<elements>
    <elemet>
        <type></type>
        <property1></property1>
        <property2></property2>
        <items>
            <item>
                <id></id>
                <name></name>
            </item>
            ...
            <item>
                <id></id>
                <name></name>
            </item>
        </items>
    </element>
</elements>

我应该将此构造转换为具有嵌套项目列表的元素,而不是将每个项目转换为多个元素.这是Element类的示例:

class Element {
    Integer type;
    String property1;
    String property2;
    Integer itemId;
    String itemName; 
}

我想在解组后得到它们的清单.对于所有列表元素,Type,property1和property2值应该相同.
有没有可能使用JAXB解决这个问题?

解决方法

您需要定义自定义 XmlAdapter.在您的情况下,复杂的部分是您要将一个XML元素映射到多个Java Element对象.这意味着,在Java中,需要配置XmlAdapter以收集Element对象.假设您的示例XML片段是文档的一部分:

<document>
   <elements> 
      <element>
          ....
      </element>
   <elements>
</document>

然后,您需要为List< Element>配置XmlAdapter. Java Document类中的字段:

class Document {
     @XmlJavaTypeAdapter(CustomAdapter.class)
     List<Element> elements;
}

然后,您的CustomAdapter类可以接收Element对象列表(对应于具有嵌套项的实际XML结构),并生成具有所需结构的Element列表.

例如,请检查JAXB XmlAdapter – Customized Marshaling and Unmarshaling

我们今天的关于使用JAXB解组/编组List cjson解析数组的分享已经告一段落,感谢您的关注,如果您想了解更多关于java JAXB 如何处理 List>、Java List list=new ArrayList();为什么要声明为List,而不是ArrayList、java – JAXB解组树结构、java – 使用JAXB解组嵌套的xml项列表的相关信息,请在本站查询。

本文标签: