Java 放心 - 将响应 JSON 反序列化为 List<POJO>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21725093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rest Assured - deserialize Response JSON as List<POJO>
提问by Wojtek
I have a POJO Artwork
. I'm retrieving a List
of those objects from a RESTful webservice in the HTTP response body in JSON format. I'm trying to write a Rest Assured-based test that would analyze the returned list. The code looks like this:
我有一个 POJO Artwork
。我正在List
以 JSON 格式从 HTTP 响应正文中的 RESTful Web 服务中检索这些对象。我正在尝试编写一个基于 Rest Assured 的测试来分析返回的列表。代码如下所示:
Response response = get("/artwork");
List returnedArtworks = response.getBody().as(List.class)
The problem is, I can't get Rest Assured to parse the returned JSON as List<Artwork>
. Instead, I get a List<LinkedHashMap>
. The map has a proper structure, i.e. could be mapped by Hymanson to Artwork
object, but I'd like to avoid mapping it manually.
问题是,我无法让 Rest Assured 将返回的 JSON 解析为List<Artwork>
. 相反,我得到了一个List<LinkedHashMap>
. 该地图具有适当的结构,即可以由 Hymanson 映射到Artwork
对象,但我想避免手动映射它。
JSON mappings in my model are OK, because when I map single object like this:
我的模型中的 JSON 映射是可以的,因为当我像这样映射单个对象时:
Artwork returnedArtwork = response.getBody().as(Artwork.class);
it works fine.
它工作正常。
Is it possible to get returnedArtworks
as List<Artwork>
?
是否有可能得到returnedArtworks
的List<Artwork>
?
采纳答案by volatilevar
You can do this:
你可以这样做:
List<Artwork> returnedArtworks = Arrays.asList(response.getBody().as(Artwork[].class));
The trick is to deserialize JSON to an array of objects (because there is no difference between the JSON string of an array or a list), then convert the array to a list.
诀窍是将 JSON 反序列化为对象数组(因为数组或列表的 JSON 字符串之间没有区别),然后将数组转换为列表。
回答by Purushotham
By using Google's Gson library you can easily parse it to List<Artwork>
. Try below code
通过使用 Google 的 Gson 库,您可以轻松地将其解析为List<Artwork>
. 试试下面的代码
Gson gson = new Gson();
List<Artwork> returnedArtworks = gson.fromJson(jsonStr, new TypeToken<List<Artwork>>(){}.getType());
//* where jsonStr is the response string(Json) receiving from your Restful webservice
回答by Seren
this solution works for version 3.0.2 (io.restassured):
此解决方案适用于版本 3.0.2 (io.restassured):
JsonPath jsonPath = RestAssured.given()
.when()
.get("/order")
.then()
.assertThat()
.statusCode(Response.Status.OK.getStatusCode())
.assertThat()
.extract().body().jsonPath();
List<Order> orders = jsonPath.getList("", Order.class);
This will extract the objects for a structure like this:
这将为这样的结构提取对象:
public class Order {
private String id;
public String getId(){
return id; }
public void setId(String id){
this.id = id;
}
}
with the given json:
使用给定的 json:
[
{ "id" : "5" },
{ "id" : "6" }
]
回答by Vytautas
With REST assured 3.0.2 you can simply check if content exists in the array
使用 REST 保证 3.0.2,您可以简单地检查数组中是否存在内容
when().get("/artwork").then().body("artworks", hasItem("some art");
//or check multiple values in array
when().get("/artwork").then().body("artworks", hasItems("some art", "other art");
This way you will avoid complexity in your code by converting JSON to list more examples how to check response content can be found link
通过这种方式,您将通过转换 JSON 以列出更多示例来避免代码的复杂性,如何检查响应内容可以找到链接
回答by Jmini
Rest-assured provide an as(java.lang.reflect.Type)
next to the version expecting a Class
used in the question.
Rest-assured 提供as(java.lang.reflect.Type)
期望Class
在问题中使用的版本旁边的一个。
java.lang.reflect.Type type; //TODO defines the type.
Response response = get("/artwork");
List<Artwork> returnedArtworks = response.getBody().as(type)
In my opinion the way the type
variable depends from the serialization lib that is used.
在我看来,type
变量的方式取决于所使用的序列化库。
If using Gson, as pointed out by Purushotham's answer, TypeToken
can be used. I prefer using it directly in rest-assured:
如果使用 Gson,正如Purushotham 的回答所指出的那样,TypeToken
可以使用。我更喜欢在放心的情况下直接使用它:
Type type = new TypeToken<List<Artwork>>(){}.getType();
Response response = get("/artwork");
List<Artwork> returnedArtworks = response.getBody().as(type)
When using Hymanson, the solution is to use the TypeFactory
(javadoc, source) to tell to which type it should be de-serialized:
使用 Hymanson 时,解决方案是使用TypeFactory
( javadoc, source) 告诉它应该反序列化为哪种类型:
Type type = TypeFactory.defaultInstance().constructCollectionLikeType(ArrayList.class, Artwork.class);
Response response = get("/artwork");
List<Artwork> returnedArtworks = response.getBody().as(type)