본문 바로가기
SpringBoot

Java conver t JsonArray to List

by ByteBridge 2021. 10. 31.
반응형
public static <T> List<T> jsonArrayToObjectList(String json, Class<T> target) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    CollectionType listType = mapper.getTypeFactory()
        .constructCollectionType(ArrayList.class, target);
    List<T> ts = mapper.readValue(json, listType);
    log.debug("TargetClass: {}", ts.get(0).getClass().getName());
    return ts;
  }
  
  //TargetClass
  class Target {}
  
  //sample json array
  private static String transaction = "[\n"
      + "  {\n"
      + "    \"payment_details\": {\n"
      + "      \"payment\": {\n"
      + "        \"amount\": 86.68,\n"
      + "        \"amount_from_ps\": 86.68,\n"
      + "        \"currency\": \"RUB\"\n"
      + "      },\n"
      + "      \"sales_tax\": {\n"
      + "        \"amount\": 20.0,\n"
      + "        \"percent\": 3.0\n"
      + "      }\n"
      + "    },\n"
      + "    \"purchase\": {\n"
      + "      \"pin_codes\": {\n"
      + "        \"amount\": null,\n"
      + "        \"content\": null,\n"
      + "        \"currency\": null\n"
      + "      },\n"
      + "      \"simple_checkout\": {\n"
      + "        \"amount\": 0,\n"
      + "        \"currency\": \"RUB\"\n"
      + "      },\n"
      + "      \"subscription\": {\n"
      + "        \"name\": null\n"
      + "      },\n"
      + "      \"virtual_currency\": {\n"
      + "        \"amount\": 0,\n"
      + "        \"name\": \"Maple\"\n"
      + "      },\n"
      + "      \"virtual_items\": \"Duck\"\n"
      + "    },\n"
      + "    \"transaction\": {\n"
      + "      \"dry_run\": 2,\n"
      + "      \"external_id\": \"P00000992\",\n"
      + "      \"id\": 141819657,\n"
      + "      \"is_refund_allowed\": 1,\n"
      + "      \"payment_method\": {\n"
      + "        \"id\": 98,\n"
      + "        \"name\": \"PayPal\"\n"
      + "      },\n"
      + "      \"project\": {\n"
      + "        \"id\": 89753,\n"
      + "        \"name\": \"Farm II Project\"\n"
      + "      },\n"
      + "      \"refund_reason\": \"Test payment\",\n"
      + "      \"status\": \"canceled\",\n"
      + "      \"transfer_date\": \"2019-02-08T10:14:08.000Z\"\n"
      + "    },\n"
      + "    \"user\": {\n"
      + "      \"country\": \"RU\",\n"
      + "      \"custom\": null,\n"
      + "      \"email\": \"j.johns@transaction.com\",\n"
      + "      \"id\": \"j.johns\",\n"
      + "      \"name\": \"j.johns\",\n"
      + "      \"phone\": null\n"
      + "    }\n"
      + "  }\n"
      + "]";
      
List<Target> result = Utils.jsonArrayToObjectList(transaction, Target.class);
반응형

'SpringBoot' 카테고리의 다른 글

Spring mvc async rest api  (0) 2021.11.07
java excell downloader in spring boot  (0) 2021.10.31
LocalDateTime hour step  (0) 2021.10.31
ModelMapper 를 사용하여 객체 컨버팅 하기  (0) 2021.05.23
Spring AOP  (0) 2020.12.06