Deserting into a class with the specified response key in jackson

Im getting a response from an external api

"success": true,
    "data": [
        {}

I would like to match only the data and the corresponding array as an entire class. Right now I have a shell, but for that, the class is +1.

public class YYYYYY {

    private boolean success;
    @JsonProperty(value = "data")
    private List<PipeDriveContact> arrayData;
+4
source share
4 answers

If you absolutely do not need other keys in the outermost object, you can parse the array using key "data" and then parse it separately in your POJO. Below is my rough implementation:

First analyze the data array:

String json = "{\"success\": true,\"data\": [{\"test\": \"some data\"}]}";

JSONObject obj = new JSONObject(json);
String data = obj.getJSONArray("data").toString();

Then, using Jackson (or something else), create an ArrayList with your required objects:

ObjectMapper objectMapper = new ObjectMapper();
TypeReference<ArrayList<PipeDriveContact>> typeRef = new TypeReference<ArrayList<PipeDriveContact>>() {};
ArrayList<PipeDriveContact> dataArray = objectMapper.readValue(data, typeRef);

The following is a POJO model created for testing:

public class PipeDriveContact {
    private String test;

    public String getTest() { return test; }

    public void setTest(String test) { this.test = test; }
}

The following are the dependencies that I used:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20171018</version>
</dependency>

Hope this helps.

0

, , , , , @JsonIgnoreProperties(ignoreUnknown = true):

@JsonIgnoreProperties(ignoreUnknown = true)
public class YYYYYY {

@JsonProperty(value = "data")
private List<PipeDriveContact> arrayData;
0

fooobar.com/questions/1688260/...

String jsonStr = "{\"success\": true,\"data\": [{\"test\": \"some data\"}]}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonStr);
ArrayNode arrayNode = (ArrayNode) node.get("data");
System.out.println(arrayNode);
List<PipeDriveContact> pojos = mapper.readValue(arrayNode.toString(), new TypeReference<List<PipeDriveContact>>() {});

System.out.println(pojos);

( toString())

[{\"test\": \"some data\"}] // the json array 

But believe me, if you don’t have a very good reason (than “I don’t want another class”), I would dissuade you from this path, and instead implement it with a wrapper class and call it. Reason: in the future, you can create your Pojos from a contract (JAON scheme), or you can use it for the "success" field.

0
source

Source: https://habr.com/ru/post/1688258/


All Articles