[英]java rest returning response with json to postman - syntax error: unexpected 'S'
使用郵遞員時,出現以下錯誤
語法錯誤:意外的“ 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": []
}
您的輸出文本不是有效的JSON。 問題在於列表的序列化方式。
我相信足以為您的JSON庫提供完整列表:
public String getJsonFromPets(List<Pet> pets) {
return gson.toJson(pets);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.