0

我有一个 Web 服务 REST:

@Path("/Vehicles")    
public class Vehicles{
        @GET
        @Path("/Cars")
        @Produces(aplicattion/json)
        public String Cars() {

            Car[] cars = Consulting my database...

            Gson gson = new Gson();

            return gson.toJson(cars); 
        }

我使用网络服务:

  try {

            HttpClient httpClient = new DefaultHttpClient();

            HttpGet get = new HttpGet(
                    "http://localhost:8080/Concessionaire/rest/Vehicles/Cars");

            HttpResponse resp = httpClient.execute(get);

            String respGET = EntityUtils.toString(resp.getEntity());

            Gson gson = new Gson();

            Cars[] c = gson.fromJson(respGET,Cars[].class);

   }catch(Exception e){

   }

但是出现了这个异常: Expected BEGIN_ARRAY but was String at line 1 colum 6 有什么问题?

4

1 回答 1

1

您的方法返回一个字符串

public String Cars() 

客户端代码需要一个 Car 数组

Cars[] c = gson.fromJson(respGET,Cars[].class);

Gson 在解析 json 时需要 BEGIN_ARRAY 事件,但会找到一个字符串。要修复它,请使用 jersey 类发送 Cars[]Response并将返回类型更改为Response.

return Response.ok(myCarsArray).build();
于 2013-04-07T12:41:59.140 回答