Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Get方法返回XML和JSON_Java_Xml_Json_Rest_Get - Fatal编程技术网

Java Get方法返回XML和JSON

Java Get方法返回XML和JSON,java,xml,json,rest,get,Java,Xml,Json,Rest,Get,如果我这样做: @GET @Path("/users") @Produces("application/json") public String users() { String users = null; ArrayList<User> userList = new ArrayList<User>(); try { userList = new UserMa

如果我这样做:

@GET
    @Path("/users")
    @Produces("application/json")
    public String users()
    {
        String users = null;
        ArrayList<User> userList = new ArrayList<User>();

        try {
                userList = new UserManager().getUsers();
                Gson gson = new Gson();
        users = gson.toJson(userList);

    } catch (Exception e) {
                e.printStackTrace();
        }
        return users;
    }
@GET
@路径(“/users”)
@生成(“应用程序/json”)
公共字符串用户()
{
字符串用户=null;
ArrayList userList=新的ArrayList();
试一试{
userList=newusermanager().getUsers();
Gson Gson=新的Gson();
users=gson.toJson(userList);
}捕获(例外e){
e、 printStackTrace();
}
返回用户;
}
我的GET方法只是重新运行JSON中的信息。 但我希望它也返回XML?类似于
@的东西产生({“application/xml”、“application/json”})


我怎么做呢?

我不确定您在这里使用的是什么框架,但这并不特别重要——您不能在同一个请求中同时返回两种格式(以合理的方式)。
Content-Type
头对于给定的响应只存在一次,因此它不能同时是
application/json
application/xml


这里的常用习惯用法是允许使用
GET
参数,该参数指定客户端希望返回数据的格式-ala
http://example.com/path/to/rest/data?type=JSON
http://example.com/path/to/rest/data?type=XML

但就像我将信息转换为JSON一样(
users=gson.toJson(userList);
),我也不必将其转换为XML?这里的要点是,您一次只能返回一种类型。您仍然需要转换为您想要返回的任何类型,但不能在同一个回答中同时返回它们。也许还有第二个问题,关于如何返回
应用程序/XML
数据。