[Bài 15] Convert json sang POJO (2) – Khi value có thể là 1 phần tử (object) hoặc nhiều phần tử (array)

Đây là 1 trường hợp hiếm gặp nhưng cũng không phải là không có.

  • Khi value là 1 phần tử dạng object
{
  "result": {
    "date": "20-7-2022",
    "value": 1
  }
}
  • Khi value là nhiều phần tử dạng array
{
  "result": [
    {
      "date": "20-7-2022",
      "value": 1
    },
    {
      "date": "2-8-2022",
      "value": 2
    }
  ]
}

Jackson hỗ trợ việc tự detect xem cái đó là 1 phần tử hay nhiều phần tử rồi gom chung lại hết thành List. Nếu chỉ là 1 phần tử thì sẽ là 1 List có 1 phần tử.

import com.fasterxml.jackson.annotation.JsonFormat;
import io.restassured.response.Response;
import lombok.Data;
import org.junit.jupiter.api.Test;

import java.util.List;

import static io.restassured.RestAssured.given;

public class MappingJacksonTest {

    @Data
    static class Wrapper {
        @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
        public List<Result> result;
    }

    @Data
    static class Result {
        public String date;
        public int value;
    }

    @Test
    void name() {
        Response res = given().get("https://extendsclass.com/mock/rest/172d73cdc37983f088b057b64047da5c/1");
        Wrapper wrapper = res.as(Wrapper.class);
        System.out.println(wrapper.getResult().get(0).getDate());
    }

    @Test
    void name2() {
        Response res = given().get("https://extendsclass.com/mock/rest/172d73cdc37983f088b057b64047da5c/2");
        Wrapper wrapper = res.as(Wrapper.class);
        System.out.println(wrapper);
    }
}
  • Bạn cần đánh dấu @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) vào field nào muốn Jackson chú ý đến. Trong ví dụ là field result, sau đó Jackson sẽ tự làm phần còn lại.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments