Developer Cafe

Json value 값에서 특정데이터 입력시 요구데이터 값들 가져오기 본문

JAVA

Json value 값에서 특정데이터 입력시 요구데이터 값들 가져오기

개발자 카페 2021. 8. 5. 14:22
728x90

※ 본 포스터는 이전 포스터 연장선입니다.

 

이전 포스터에서 Json으로 불러오니 json value 값이 다음 배열의 json key 값으로 들어가는걸 알게 되었다.

 

위의 API 를 주고 이걸 JAVA로 바꿔 차이름 입력시 model과 code가 나오게 해달라 라고 하셨다.

복잡한 요구사항이 있어 설계를 했다.

  1. 시작일과 종료일은 오늘날짜와 내일날짜로 고정하기 때문에 Date를 불러오는 메서드를 만든다.
  2. 입력데이터가 있냐없냐, 데이터가 하나냐 여러개냐에 따라 나뉘기 때문에 body부분을 분리한다.
  3. API 요청 후 응답값이 PHP형태이므로 이를 JAVA형태로 만들 필요가 있기 때문에 관련메서드를 만든다.
  4. 받은 Json 데이터에서 차량 이름과 아이디를 알아내야될 필요가 있으므로 이를 얻는 메서드를 만든다.
  5. 이름과 이이디를 받아 CarListResDto 형태로 다시 파싱해야되기에 makeResult 메서드를 만든다.

1. 시작일과 종료일은 오늘날짜와 내일날짜로 고정하기 때문에 Date를 불러오는 메서드를 만든다.

public List<String> getDate() {
    List<String> dates = new ArrayList<>();

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    cal.add(Calendar.DATE, 1);
    String datestr1 = sdf.format(cal.getTime());
    cal.add(Calendar.DATE, 1);
    String datestr2 = sdf.format(cal.getTime());

    dates.add(datestr1);
    dates.add(datestr2);

    return dates;
  }

2. 입력데이터가 있냐없냐, 데이터가 하나냐 여러개냐에 따라 놔뉘기 때문에 body부분을 분리한다.

public String makeBody() {
    String datestr1 = getDate().get(0);
    String datestr2 = getDate().get(1);

    List<BasicInfoDto> setBasicInfo = new ArrayList<>();
//    setBasicInfo.add(new BasicInfoDto("", "", ""));
//    setBasicInfo.add(new BasicInfoDto("테스트렌트카", "naturemb", "naturemb1"));
//    setBasicInfo.add(new BasicInfoDto("조아렌트카", "naturemb", "naturemb1"));

    BasicInfoDto[] arr = setBasicInfo.toArray(new BasicInfoDto[setBasicInfo.size()]);

    String body = "";
    if (arr.length!=0) {
      for (int i=0 ; i<arr.length ; i++) {
        if (i!=0) {
          body+="&";
        }
        body += "call_company["+i+"][company]="+arr[i].getCompany()+"&call_company["+i+"][pmid]="+arr[i].getPmid()
          +"&call_company["+i+"][pmpw]="+arr[i].getPmpw();
        if (arr.length - 1 == i) {
          body += "&st="+datestr1+"0900&et="+datestr2+"0900";
        }
      }
    }
    if (arr.length==0) {
      body += "call_company[0][company]=&call_company[0][pmid]=&call_company[0][pmpw]=&st="+datestr1+"0900&et="+datestr2+"0900";
    }
    return body;
  }

3. API 요청 후 응답값이 PHP형태이므로 이를 JAVA형태로 만들 필요가 있기 때문에 관련메서드를 만든다.

public JsonNode getJsonResult() {
    String body = makeBody();

    Map<String, String> headers = new LinkedHashMap<>();
    headers.put("Content-Type", "application/x-www-form-urlencoded");

    WebClient.RequestHeadersSpec<?> request = WebClient.create("https://rentapi.mygrim.com")
      .post()
      .uri("/basicv2/carlist.php")
      .headers(httpHeader -> httpHeader.setAll(headers))
      .syncBody(body)
      .accept(MediaType.APPLICATION_JSON)
      .acceptCharset(Charset.forName("UTF-8"));

    String result = request.exchange().timeout(Duration.ofMillis(10000)).block().bodyToMono(String.class).block();

    ObjectMapper mapper = new ObjectMapper();
    JsonNode treeNode = null;

    try {
      treeNode = mapper.readValue(result, JsonNode.class);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ArithmeticException e) {
      e.printStackTrace();
    }

    return treeNode;
  }

4. 받은 Json 데이터에서 차량 이름과 아이디를 알아내야될 필요가 있으므로 이를 얻는 메서드를 만든다.

public String[] getCompanyName(PostData getPostData) {
    int callCompanySize = getPostData.getCall_company().size();

    String[] companyName = new String[callCompanySize];
    for (int i=0 ; i<callCompanySize ; i++) {
      companyName[i] = getPostData.getCall_company().get(i).getCompany();
    }
    return companyName;
  }

  public String[] getPmidName(PostData getPostData) {
    int callCompanySize = getPostData.getCall_company().size();

    String[] pmidName = new String[callCompanySize];
    for (int i=0 ; i<callCompanySize ; i++) {
      pmidName[i] = getPostData.getCall_company().get(i).getPmid();
    }
    return pmidName;
  }

5. 이름과 이이디를 받아 CarListResDto 형태로 다시 파싱해야되기에 makeResult 메서드를 만든다.

public void makeResult(JsonNode company, String[] companyName, String[] pmidName) throws IOException {
    List<String> code = new ArrayList<>();
    List<String> model = new ArrayList<>();

    ObjectMapper mapper = new ObjectMapper();

    List<CarListResDto> carListResDtos = new ArrayList<>();

    for (int i=0 ; i< companyName.length ; i++) {
      JsonNode companyRentCar = company.get(companyName[i]);
      JsonNode naturemb = companyRentCar.get(pmidName[i]);

      ObjectReader readerNaturemb = mapper.readerFor(new TypeReference<List<Naturemb>>() {});
      List<Naturemb> listNaturemb = readerNaturemb.readValue(naturemb);

      for (int j=0 ; j<listNaturemb.size() ; j++) {
        code.add(listNaturemb.get(j).getCode());
        model.add(listNaturemb.get(j).getModel());

        CarListResDto.Agency agency = new CarListResDto.Agency();
        agency.setName(companyName[i]);

        CarListResDto.Car car = new CarListResDto.Car();
        car.setName(model.get(j));
        car.setCode(code.get(j));

        carListResDtos.add(new CarListResDto(agency, car));
      }

      code = new ArrayList<>();
      model = new ArrayList<>();
    }

    Gson gson = new Gson();
    String jsonString = gson.toJson(carListResDtos);
    System.out.println(jsonString);
  }

 

test multy 실행 코드

@Test
  public void multy() throws IOException {
    JsonNode treeNode = getJsonResult();

    ObjectMapper mapper = new ObjectMapper();
    if (treeNode.get("postdata")==null) {
      System.out.println(treeNode);
      return;
    }
    JsonNode postdata = treeNode.get("postdata");

    ObjectReader readerPostdata = mapper.readerFor(new TypeReference<PostData>() {});

    PostData getPostData = readerPostdata.readValue(postdata);

    JsonNode company = treeNode.get("company");

    String[] companyName = getCompanyName(getPostData);
    String[] pmidName = getPmidName(getPostData);

    makeResult(company, companyName, pmidName);

  }

test java 전체 코드

package com.example.rentcar;

import com.example.rentcar.domain.*;
import com.example.rentcar.dto.BasicInfoDto;
import com.example.rentcar.dto.CarListResDto;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.gson.Gson;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.reactive.function.client.WebClient;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@RunWith(SpringRunner.class)
public class SimpleTest {

  public List<String> getDate() {
    List<String> dates = new ArrayList<>();

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    cal.add(Calendar.DATE, 1);
    String datestr1 = sdf.format(cal.getTime());
    cal.add(Calendar.DATE, 1);
    String datestr2 = sdf.format(cal.getTime());

    dates.add(datestr1);
    dates.add(datestr2);

    return dates;
  }

  public String makeBody() {
    String datestr1 = getDate().get(0);
    String datestr2 = getDate().get(1);

    List<BasicInfoDto> setBasicInfo = new ArrayList<>();
//    setBasicInfo.add(new BasicInfoDto("", "", ""));
//    setBasicInfo.add(new BasicInfoDto("테스트렌트카", "naturemb", "naturemb1"));
//    setBasicInfo.add(new BasicInfoDto("조아렌트카", "naturemb", "naturemb1"));

    BasicInfoDto[] arr = setBasicInfo.toArray(new BasicInfoDto[setBasicInfo.size()]);

    String body = "";
    if (arr.length!=0) {
      for (int i=0 ; i<arr.length ; i++) {
        if (i!=0) {
          body+="&";
        }
        body += "call_company["+i+"][company]="+arr[i].getCompany()+"&call_company["+i+"][pmid]="+arr[i].getPmid()
          +"&call_company["+i+"][pmpw]="+arr[i].getPmpw();
        if (arr.length - 1 == i) {
          body += "&st="+datestr1+"0900&et="+datestr2+"0900";
        }
      }
    }
    if (arr.length==0) {
      body += "call_company[0][company]=&call_company[0][pmid]=&call_company[0][pmpw]=&st="+datestr1+"0900&et="+datestr2+"0900";
    }
    return body;
  }

  public JsonNode getJsonResult() {
    String body = makeBody();

    Map<String, String> headers = new LinkedHashMap<>();
    headers.put("Content-Type", "application/x-www-form-urlencoded");

    WebClient.RequestHeadersSpec<?> request = WebClient.create("https://rentapi.mygrim.com")
      .post()
      .uri("/basicv2/carlist.php")
      .headers(httpHeader -> httpHeader.setAll(headers))
      .syncBody(body)
      .accept(MediaType.APPLICATION_JSON)
      .acceptCharset(Charset.forName("UTF-8"));

    String result = request.exchange().timeout(Duration.ofMillis(10000)).block().bodyToMono(String.class).block();

    ObjectMapper mapper = new ObjectMapper();
    JsonNode treeNode = null;

    try {
      treeNode = mapper.readValue(result, JsonNode.class);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ArithmeticException e) {
      e.printStackTrace();
    }

    return treeNode;
  }

  public String[] getCompanyName(PostData getPostData) {
    int callCompanySize = getPostData.getCall_company().size();

    String[] companyName = new String[callCompanySize];
    for (int i=0 ; i<callCompanySize ; i++) {
      companyName[i] = getPostData.getCall_company().get(i).getCompany();
    }
    return companyName;
  }

  public String[] getPmidName(PostData getPostData) {
    int callCompanySize = getPostData.getCall_company().size();

    String[] pmidName = new String[callCompanySize];
    for (int i=0 ; i<callCompanySize ; i++) {
      pmidName[i] = getPostData.getCall_company().get(i).getPmid();
    }
    return pmidName;
  }

  public void makeResult(JsonNode company, String[] companyName, String[] pmidName) throws IOException {
    List<String> code = new ArrayList<>();
    List<String> model = new ArrayList<>();

    ObjectMapper mapper = new ObjectMapper();

    List<CarListResDto> carListResDtos = new ArrayList<>();

    for (int i=0 ; i< companyName.length ; i++) {
      JsonNode companyRentCar = company.get(companyName[i]);
      JsonNode naturemb = companyRentCar.get(pmidName[i]);

      ObjectReader readerNaturemb = mapper.readerFor(new TypeReference<List<Naturemb>>() {});
      List<Naturemb> listNaturemb = readerNaturemb.readValue(naturemb);

      for (int j=0 ; j<listNaturemb.size() ; j++) {
        code.add(listNaturemb.get(j).getCode());
        model.add(listNaturemb.get(j).getModel());

        CarListResDto.Agency agency = new CarListResDto.Agency();
        agency.setName(companyName[i]);

        CarListResDto.Car car = new CarListResDto.Car();
        car.setName(model.get(j));
        car.setCode(code.get(j));

        carListResDtos.add(new CarListResDto(agency, car));
      }

      code = new ArrayList<>();
      model = new ArrayList<>();
    }

    Gson gson = new Gson();
    String jsonString = gson.toJson(carListResDtos);
    System.out.println(jsonString);
  }

  @Test
  public void multy() throws IOException {
    JsonNode treeNode = getJsonResult();

    ObjectMapper mapper = new ObjectMapper();
    if (treeNode.get("postdata")==null) {
      System.out.println(treeNode);
      return;
    }
    JsonNode postdata = treeNode.get("postdata");

    ObjectReader readerPostdata = mapper.readerFor(new TypeReference<PostData>() {});

    PostData getPostData = readerPostdata.readValue(postdata);

    JsonNode company = treeNode.get("company");

    String[] companyName = getCompanyName(getPostData);
    String[] pmidName = getPmidName(getPostData);

    makeResult(company, companyName, pmidName);

  }

}

CarListResDto 코드

package com.example.rentcar.dto;

import lombok.*;

@Data
public class CarListResDto {

  private Agency agency;
  private Car car;

  public CarListResDto(Agency agency, Car car) {
    this.agency = agency;
    this.car = car;
  }

  @Data
  public static class Agency {
    private String name;
  }

  @Data
  public static class Car {
    private String name;
    private String code;

  }

}

결과 입력한 데이터가 존재할시 System.out.println값을 JsonParser를 통해 출력

 

결과 입력한 데이터가 존재하지 않을시 System.out.println값을 JsonParser를 통해 출력

 

Naturemb 클래스

@Getter
@Setter
@ToString
public class Naturemb {

  private String code;
  private String model;
  private String group;
  private String fuel;
  private int possible;
  private String defaultfee;
  private String salefee;
  private int rate;
  private String options;
  private String years;
  private int people;
  private String driverold;
  private String drivercareer;
  private String driverlicence;
  private String driverpermit;
  private String pcode;
  private List<Bohum> bohum;
  private List<Event> event;
  private List<SpGoods> sp_goods;

}

Bohum 클래스

@Getter
@Setter
@ToString
public class Bohum {

  private String code;
  private String name;
  private String salefee;
  private String salefeetxt;
  private String memo;
  private String avoidfee;
  private String limitfee;
  private String driverold;
  private String drivercareer;
  private int driverlicence;
  private String driverpermit;
  private String flag1;
  private String flag2;

}

Event 클래스

@Setter
@Getter
@ToString
public class Event {

  private String code;
  private String name;
  private String defaultfee;
  private String salefee;
  private int rate;
  private String type;
  private String typeko;
}

SpGoods 클래스

@ToString
@Setter
@Getter
public class SpGoods {

  private String code;
  private String name;
  private int salefee;

}
728x90

'JAVA' 카테고리의 다른 글

PHP Json형태를 JAVA Json형태로 변경하기  (1) 2021.08.05
사례를 통해 JAVA코드로 달력 구현하기  (0) 2021.06.23
Optional  (0) 2021.05.21
DTO 설계하기  (0) 2021.05.11
JIT 컴파일러 (Just-In-Time 컴파일러)  (0) 2021.03.06
Comments