[Java] JSON communication with jackson

Communicate json with java (using jackson)

environment

As usual, it's a memorandum ...

order

  1. Dto generation
  2. Convert to Dto-> json using jackson
  3. Communicate using HttpURLConnection
  4. Get results

Dto generation

public class SampleDto implements Serializable {
    private static final long serialVersionUID = 1L;  //It is better to generate it properly

    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 conversion

	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;
		}
	}

communication

	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;
	}

Get results

	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;
	}

Thank you for your hard work!

Recommended Posts

[Java] JSON communication with jackson
JSON with Java and Jackson Part 2 XSS measures
I tried UDP communication with Java
Try bidirectional communication with gRPC Java
Memo when HTTP communication with Java (OkHttp)
Diffed with JSON
Working with huge JSON in Java Lambda
Install java with Homebrew
Read JSON in Java
Change seats with java
Install Java with Ansible
Import JSON with SolrJ
Comfortable download with JAVA
JSON validation with JSON schema
Handle JSON with minimal-json
Switch java with direnv
Java Network Basics (Communication)
POST JSON in Java
Download Java with Ansible
Create JSON in Java
Let's scrape with Java! !!
Format JSON with org.json
Build Java with Wercker
Endian conversion with JAVA
Convert JSON and YAML in Java (using Jackson and SnakeYAML)
Convert Java enum enums and JSON to and from Jackson
[Java] Convert JSON to Java and Java to JSON-How to use GSON and Jackson-
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java
Java multi-project creation with Gradle
Getting Started with Java Collection
Java Config with Spring MVC
Basic Authentication with Java 11 HttpClient
Let's experiment with Java inlining
Run batch with docker-compose with Java batch
Rewrite Java try-catch with Optional
Install Java 7 with Homebrew (cask)
JSON in Java and Jackson Part 1 Return JSON from the server
Java to play with Function
How to use JSON data in WebSocket communication (Java, JavaScript)
Try DB connection with Java
Enable Java EE with NetBeans 9
[Java] JavaConfig with Static InnerClass
Try gRPC with Java, Maven
Let's operate Excel with Java! !!
Version control Java with SDKMAN
RSA encryption / decryption with java 8
Paging PDF with Java + PDFBox.jar
Sort strings functionally with java
Object-oriented (java) with Strike Gundam
[Java] Content acquisition with HttpCliient
Java version control with jenv
Troubleshooting with Java Flight Recorder
[Java] [jackson] Corresponds to the trailing comma (trailing comma) when parsing JSON.
Streamline Java testing with Spock
Connect to DB with Java
Connect to MySQL 8 with Java
Error when playing with java
Using Mapper with Java (Spring)
Java study memo 2 with Progate
POST Json in Java ~ HttpURLConnection ~