java rest将带有json的响应返回给邮递员-语法错误:意外的'S'

时间:2018-09-22 15:30:02

标签: java json rest postman

使用邮递员时,出现以下错误

语法错误:意外的“ S”

即使我的JSON字符串看起来不错。我看过类似的主题,通常说是给响应对象一个可以正确转换为JSON的实体。我已经用GSON解析了宠物清单。

代码:

@Path("Pet")
public class PetResource {

    @Context
    private UriInfo context;

    public PetResource() {
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getJson() {
        PetMapper pm = new PetMapper();
        JSONConverter jsonconv = new JSONConverter();
        List<Pet> petList = pm.getPets();
        String json = jsonconv.getJsonFromPets(petList);
        return Response.ok().entity(json).build();
    }

    @PUT
    @Path("/size")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response getPetSize() {
        PetMapper pm = new PetMapper();
        return Response.ok(pm.getPetSize()).build();
    }
}

GSon转换器

public class JSONConverter {

    static Gson gson = new GsonBuilder().setPrettyPrinting().create();

public String getJsonFromPets(List<Pet> pets) {
    String petsString = "";
    for (Pet pet : pets) {
        petsString += gson.toJson(pet) + " ";
    }
    return petsString;
}
}

以下是我的原始回复

{
  "id": 1,
  "name": "Fiddo",
  "birth": "2015-02-01",
  "species": "Dog",
  "owner_id": 1,
  "events": []
} {
  "id": 2,
  "name": "Hannibal",
  "birth": "2013-05-10",
  "species": "Dog",
  "owner_id": 1,
  "events": []
} {
  "id": 3,
  "name": "Elvis",
  "birth": "2010-08-08",
  "species": "Cat",
  "owner_id": 3,
  "events": []
} {
  "id": 4,
  "name": "Sam",
  "birth": "2012-01-05",
  "species": "Rabbit",
  "death": "2015-07-07",
  "owner_id": 2,
  "events": []
} 

1 个答案:

答案 0 :(得分:2)

您的输出文本不是有效的JSON。问题在于列表的序列化方式。

我相信足以为您的JSON库提供整个列表:

public String getJsonFromPets(List<Pet> pets) {
    return gson.toJson(pets);
}