LoginSignup
0
0

More than 3 years have passed since last update.

【Java】JSON 通信 with jackson

Last updated at Posted at 2020-09-23

java で json の通信を行う (jackson を利用)

環境

  • windows10
  • eclipse:2020-06 (4.16.0)
  • jackson
  • java 1.8

例によって忘備録です・・・

順序

  1. Dto 生成
  2. jackson を使って Dto -> json に変換
  3. HttpURLConnection を使って通信
  4. 結果取得

Dto 生成

public class SampleDto implements Serializable {
    private static final long serialVersionUID = 1L;  // ちゃんと生成した方が良さげ

    private int id;
    private String mail;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getMail() {
        return mail;
    }
    public void setMail(String mail) {
        this.mail = mail;
    }
}

Dto -> json 変換

    protected String createJson4Sample(SampleDto dto) {

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(dto);
        } catch (JsonProcessingException e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            log.error(sw.toString());
            return null;
        }
    }

通信

    protected String requestJson(String method, String json, String urlPath, String charset,
            String bearer) {

        HttpURLConnection con = null;
        if (StringUtils.isEmpty(charset)) {
            charset = StringUtils.lowerCase(StandardCharsets.UTF_8.name());
        }
        String body = "";
        try {
            URL url = new URL(urlPath);
            con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod(method);
            con.setUseCaches(false);
            con.setDoOutput(true);
            con.setRequestProperty("Content-Type", "application/json; charset=" + charset);
            if (StringUtils.isNotEmpty(bearer)) {
                con.setRequestProperty("Authorization", "Bearer "+bearer);
            }

            OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(con.getOutputStream()));
            out.write(json);
            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = in.readLine();
            while (line != null) {
                body = body + line;
                line = in.readLine();
            }
        }
        catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            log.error(sw.toString());
            return null;
        }
        finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return body;
    }

結果取得

    protected boolean checkResponseJson(String response) {

        ObjectMapper mapper = new ObjectMapper();
        try {
            if (StringUtils.isEmpty(response)) { return false; }
            JsonNode root = mapper.readTree(response);

            String success = root.get("success").asText();
            String id = root.get("id").asText();
            log.info("Response:" + id + ":" + success);
            if (!"OK".equalsIgnoreCase(success)) {
                return false;
            }
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            log.error(sw.toString());
            return false;
        }
        return true;
    }

以上、お疲れさまでした!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0