19

ジャージーを使用してRESTサービスを構築し、Collection<String>XMLとして返したいと思っています。

@GET
@Produces(MediaType.TEXT_XML)
@Path("/directgroups")
public Response getDirectGroupsForUser(@PathParam("userId") String userId) {
    try {
        Collection<String> result = service.getDirectGroupsForUser(userId, null, true);

//      return result; //first try
//      return result.toArray(new String[0]); //second try
        return Response.ok().type(MediaType.TEXT_XML).entity(result).build(); //third try
    } catch (UserServiceException e) {
        LOGGER.error(e);
        throw new RuntimeException(e.getMessage());
    }
}

しかし、私の試みは次の例外で失敗します:

javax.ws.rs.WebApplicationException:com.sun.jersey.api.MessageException:Javaクラスjava.util.ArrayList、Javaタイプクラスjava.util.ArrayList、およびMIMEメディアタイプtext/xmlのメッセージ本文ライターはそうではありませんでした見つかった

そして、グーグルで見つけたその例外に対するすべての結果は、私の状況のようにtext/xmlではなくtext/jsonを返すことを扱っていました。

誰か助けてもらえますか?Responseを使用する場合、それがXMLのルート要素であり、コレクションにその中の文字列要素のリストになると思いました。

4

4 に答える 4

47

使用する

List<String> list = new ArrayList<String>();
GenericEntity<List<String>> entity = new GenericEntity<List<String>>(list) {};
Response response = Response.ok(entity).build();

Genericエンティティラッパーは、ResponseBuilderを使用するときに出力を取得するように機能します。

参照

于 2013-08-14T19:28:11.443 に答える
12

注:この答えは機能しますが、anarの答えの方が優れています。

問題を解決するには、JAXB注釈付きクラスを使用するようにしてください。メソッドを次のように変更できます。

@GET
@Produces(MediaType.TEXT_XML)
@Path("/directgroups")
public Groups getDirectGroupsForUser(@PathParam("userId") String userId) {
    try {

        Groups groups = new Groups();
        groups.getGroup().addAll(service.getDirectGroupsForUser(userId, null, true));
        return groups;
    } catch (UserServiceException e) {
        LOGGER.error(e);
        throw new RuntimeException(e.getMessage());
    }
}

次に、グループ用にJAXB注釈付きクラスを作成します。この回答で説明されているプロセスを使用して、生成されたクラスを含めました。作成されるドキュメントの例を次に示します。

<groups>
  <group>Group1</group>
  </group>Group2</group>
</groups>

そして、生成されたクラスは次のとおりです。

package example;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for anonymous complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType>
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element ref="{}group" maxOccurs="unbounded"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "group"
})
@XmlRootElement(name = "groups")
public class Groups {

    @XmlElement(required = true)
    protected List<String> group;

    /**
     * Gets the value of the group 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 group property.
     * 
     * <p>
     * For example, to add a new item, do as follows:
     * <pre>
     *    getGroup().add(newItem);
     * </pre>
     * 
     * 
     * <p>
     * Objects of the following type(s) are allowed in the list
     * {@link String }
     * 
     * 
     */
    public List<String> getGroup() {
        if (group == null) {
            group = new ArrayList<String>();
        }
        return this.group;
    }

}
于 2013-03-28T09:27:44.620 に答える
0

これまでのところ私のために働いた唯一のことは、私自身のWrapperオブジェクトを作成することです。

@XmlRootElementアノテーションを忘れずに、 JAXBの解析方法を説明してください。

これはどのタイプのオブジェクトでも機能することに注意してください。この例では、文字列のArrayListを使用しました。

例えば

Wrapperオブジェクトは次のようになります。

import java.util.ArrayList;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class ArrayListWrapper {
    public ArrayList<String> myArray = new ArrayList<String>();
}

そして、RESTメソッドは次のようになります。

@GET
@Produces(MediaType.TEXT_XML)
@Path("/directgroups")
public ArrayListWrapper getDirectGroupsForUser(@PathParam("userId") String userId) {
    try {
        ArrayListWrapper w = new ArrayListWrapper();
        w.myArray = service.getDirectGroupsForUser(userId, null, true);
        return w;
    } catch (UserServiceException e) {
        LOGGER.error(e);
        throw new RuntimeException(e.getMessage());
    }
}
于 2017-01-02T15:02:40.710 に答える
0

返したいオブジェクトに@XmlRootElement(name = "class name")を追加すると、問題が解決しました

于 2018-03-17T12:37:37.433 に答える