반응형


파이썬 말고 Spring boot(Java)에서 슬랙 웹훅을 사용해 볼 것이다.



- 파이썬으로 Slack 통신하기

1. 2018/11/03 - [Develop/Python] - Python Slack WebHook (파이썬 슬랙 웹훅) 만들기

2. 2018/11/03 - [Develop/Python] - Python Slack Bot (파이썬 슬랙 봇) - slackclient

3. 2018/11/03 - [Develop/Python] - Python Slack Bot (파이썬 슬랙 봇) - slacker

4. 2018/11/08 - [Develop/Python] - Python Slack Lunch Bot - 점심 알리미 봇

5. 2019/05/03 - [Develop/Node.js] - [Node.js] Node.js Slack WebHooks (슬랙 웹훅)



1. 먼저 아래의 경로에 들어가서 슬랙 웹훅 추가하는 법을 보고 온다.

2018/11/03 - [Develop/Python] - Python Slack WebHook (파이썬 슬랙 웹훅) 만들기


2. 아래의 dependency를 추가한다.



  net.gpedro.integrations.slack
  slack-webhook
  1.4.0

3. 아래와 같이 연습해본다.


@GetMapping("/test")
	public void webHook() {
		
		SlackApi api = new SlackApi("https://hooks.slack.com/services/");    //웹훅URL
		api.call(new SlackMessage("#general", "TEST-WEBHOOK", "연습~~~~"));
		
	}

4. 결과





슬랙 자체에서 Java API를 많이 제공해준다
https://api.slack.com/community  - 여기에 들어가면 확인할 수 있다.

이 글에서 사용한 API는 
이것이다.


반응형
반응형


Spring boot에서 AWS S3 파일업로드 하는 방법이다.




Spring boot AWS 배포 방법

2018/10/26 - [Develop/Spring Boot] - Spring Boot AWS Elastic BeanStalk을 이용한 배포


AWS Python Lambda 사용방법

2018/11/16 - [Develop/Python] - AWS Python Lambda (CloudWatch Lambda) 사용하기



1. S3에서 버킷을 하나 생성한다.




버킷을 생성할 때 주의할 점은 이름에 대문자가 들어가면 안되고 특수문자가 들어가면안된다. 또한, 이 버킷의 이름은 AWS S3의 전체 버킷 이름들과 중복이 되면 안된다. 예를들어 test라는 버킷을 한 경우 누군가 test라는 버킷을 사용중이라면 test라는 이름으로 버킷을 생성할 수 없다.


이름을 정한 후 옵션이나 권한 설정은 필요하면 설정을 하시고 그 외 그냥 다음을 눌러 생성한다. 어차피 옵션이나 권한은 S3를 생성하고 다시 설정을 할 수 있다.




2. Spring boot pom.xml에 dependency를 추가한다.


s3 dependency를 추가한다.



    com.amazonaws
    aws-java-sdk-s3
    1.11.452


그리고 Multipartfile 을 사용할 것이기 때문에 Multipartfile dependency를 추가한다.



    commons-fileupload
    commons-fileupload
    1.3.3


3. appliaction.properties 파일 설정.


리전 정보는 옆의 링크에서 확인할 수 있다.- https://docs.aws.amazon.com/ko_kr/general/latest/gr/rande.html 

cloud.aws.credentials.accessKey=IAM USER에서 확인
cloud.aws.credentials.secretKey=IAM USER에서 확인
cloud.aws.s3.bucket=buckettestgogo
cloud.aws.region.static=ap-northeast-2

추가로 Mutlipartfile의 파일 크기 범위를 정하고 싶으면 application.properties에 아래와 같이 추가한다.


spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB

4. 파일업로드


AmazonS3 의존성을 주입하고. bucket이름을 가져온다 굳이 @Value로 안가져와도 되고 buckettestgogo를 선언해도 된다.


ObjectMetadata를 통해 ContentType을 설정할 수 있다.

그리고 CloudFront를 사용하시는 분들이라면 metadata에 setCacheControl로 Cache설정이 가능하다.

또한. 파일의 권한을 지정할 수 있다. 아래 소스에는 읽기를 Public으로 설정하였다.

	@Autowired
	private AmazonS3 amazonS3;

	@Value("${cloud.aws.s3.bucket}")
	private String bucket;

	public void s3Test(MultipartFile file, String fname) {
		TransferManager tm = TransferManagerBuilder.standard().withS3Client(amazonS3).build();


		PutObjectRequest request;
		try {
	
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setCacheControl("604800"); // 60*60*24*7 일주일
			metadata.setContentType("image/png");
			request = new PutObjectRequest(bucket, fname, file.getInputStream(), metadata)
					.withCannedAcl(CannedAccessControlList.PublicRead);
			// amazonS3.putObject(request);
			Upload upload = tm.upload(request);

			upload.waitForCompletion();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AmazonServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AmazonClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       }


기본적인 예제를 활용하여 만들어 보았다 그 외에는 AWS에서 상세히 잘 설명되어 있다.

AWS 객체업로드 - https://docs.aws.amazon.com/ko_kr/AmazonS3/latest/dev/HLuploadFileJava.html

AWS 리전정보 - https://docs.aws.amazon.com/ko_kr/general/latest/gr/rande.html

반응형
반응형


마지막으로 hashmap 을 json으로 만드는 방법과, JsonObject를 생성하는 방법이다.



Spring boot Json 1편, 2편, 3편, 4편

1. 2018/11/06 - [Spring Boot] - Spring Boot Json, JsonObject로 만들기 - JSON 1편

2. 2018/11/07 - [Develop/Spring Boot] - Spring Boot Json, Gson을 이용한 JsonObject to String, String to JsonObject- JSON 2편

3. 2018/11/09 - [Develop/Spring Boot] - Spring Boot Json, Jackson을 이용한 JsonParsing - Json 3편

4. 2018/11/12 - [Develop/Spring Boot] - Spring Boot Deserialization Json, Deserialization JsonString to JsonObject - Json 4편



번외 Database의 값을 Json으로 select하는 방법.

1. 2018/10/24 - [Spring Boot] - Spring boot jpa map, hashmap, JSON형식

2. 2018/10/28 - [Spring Boot] - Spring boot JPA EntityManager를 이용한 Map형식으로 mapping하기


Spring boot에서 MySQL JSON 타입 SELECT하는 방법

1. 2018/11/30 - [Develop/Spring Boot] - Spring boot MySQL JSON - MySQL JSON DATA TYPE 값 가져오기



HashMap을 Json으로 만드는 방법을 배우기에 앞서 JsonObject를 생성하는 방법을 먼저 본다.


1. google-json-simple을 이용한 JsonObject 만드는 방법.


xml에 아래와 같은 dependency를 추가한다.


		com.googlecode.json-simple
		json-simple
		1.1


우리가 만들어볼 Json예제는 4편에서 사용한 Json이다.


{
    "id": 1,
    "password": "1234",
    "details": [
        {
            "name": "test",
            "age": 20
        },{
            "name": "test2",
            "age": 21
        }
    ] 
}

그리고 아래와 같이 JSONObject라는 것과 JSONArray라는 것을 사용하여 JSON을 생성할 수 있다.


public void test() {
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();
		
		obj.put("id", 1);
		obj.put("password", "1234");
		
		JSONObject obj2 =new JSONObject();
		obj2.put("name", "test");
		obj2.put("age", 20);
		
		arr.add(obj2);
		
		obj2 = new JSONObject();
		obj2.put("name", "test2");
		obj2.put("age", 21);
		
		arr.add(obj2);
		
		obj.put("details", arr);
		
		System.out.println(obj.toString());
		
}




현재는 Json이 Array를 포함하여 JSONArray를 사용하였지만 일반 적인 key : value 형태는 JSONObject 하나만으로도 생성할 수 있다.


2. Gson을 이용한JsonObject 생성


이 방법은 Json  2편에서 배웠으나 이번엔 Array를 사용하기 때문에 다시 한번 해본다. 사실 위의 json-simple과 별반 다를게 없다.



	public void test() {
		Gson gson = new Gson();
		JsonObject obj = new JsonObject();
		JsonArray arr = new JsonArray();
		
		obj.addProperty("id", 1);
		obj.addProperty("password", "1234");
		
		JsonObject obj2 = new JsonObject();
		obj2.addProperty("name", "test");
		obj2.addProperty("age", 20);
		arr.add(obj2);
		
		obj2= new JsonObject();
		obj2.addProperty("name", "test2");
		obj2.addProperty("age", 21);
		
		arr.add(obj2);
		
		obj.add("details", arr);
		
		String jsonString = obj.toString();
		
		System.out.println("gson을 이용한 객체생성");
		System.out.println(jsonString);
		
	}




3. HashMap을 Json으로 만드는 방법.


HashMap<String, Object>를 선언해서 이번 편에서 했던 모든 것들(json-simple의 obj와 gson의 obj)을 HashMap에 put해보고

일반 데이터를 HashMap에 put해서 json으로 변환해 보는 법을 해본다. 그리고 gson의 prettyprinting을 이용하여 예쁘게 출력해본다.



public void test() {
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();

		obj.put("id", 1);
		obj.put("password", "1234");

		JSONObject obj2 = new JSONObject();
		obj2.put("name", "test");
		obj2.put("age", 20);

		arr.add(obj2);

		obj2 = new JSONObject();
		obj2.put("name", "test2");
		obj2.put("age", 21);

		arr.add(obj2);

		obj.put("details", arr);

		
		JsonObject g_obj = new JsonObject();
		JsonArray g_arr = new JsonArray();

		g_obj.addProperty("id", 1);
		g_obj.addProperty("password", "1234");

		JsonObject g_obj2 = new JsonObject();
		g_obj2.addProperty("name", "test");
		g_obj2.addProperty("age", 20);
		g_arr.add(g_obj2);

		g_obj2 = new JsonObject();
		g_obj2.addProperty("name", "test2");
		g_obj2.addProperty("age", 21);

		g_arr.add(g_obj2);

		g_obj.add("details", g_arr);
		
		HashMap map = new HashMap();
		map.put("json-simple", obj);
		map.put("gson", g_obj);
		map.put("HashMap", "맵테스트");
		map.put("숫자테스트", 1234567890);
		
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String jsonString = gson.toJson(map, new TypeToken>() {
		}.getType());
		System.out.println("HashMap to JSON");
		System.out.println(jsonString);

	}



이로써 Spring boot 에서의 Json에 대한 학습을 마무리한다.

1편부터 마지막편까지의 내용과 번외편 내용 2개만 알아도 Spring boot에서 모든 데이터들을 Json으로 만들 수 있다.


반응형
반응형

어찌보면 가장 중요한 Deserialization한 JsonString 형태를 파싱하는 방법이다.

Spring Boot에서 Deserialization 파싱을 위해 Jackson과 gson을 사용하면서 동시에 클래스를 생성하여 사용해야한다.

 

 

Spring boot Json 1편, 2편, 3편, 마지막

1. 2018/11/06 - [Spring Boot] - Spring Boot Json, JsonObject로 만들기 - JSON 1편

2. 2018/11/07 - [Develop/Spring Boot] - Spring Boot Json, Gson을 이용한 JsonObject to String, String to JsonObject- JSON 2편

3. 2018/11/09 - [Develop/Spring Boot] - Spring Boot Json, Jackson을 이용한 JsonParsing - Json 3편

4. 2018/11/13 - [Develop/Spring Boot] - Spring Boot Json, hashmap to json , JsonObject 만들기- JSON 마지막

 

 

번외 Database의 값을 Json으로 select하는 방법.

1. 2018/10/24 - [Spring Boot] - Spring boot jpa map, hashmap, JSON형식

2. 2018/10/28 - [Spring Boot] - Spring boot JPA EntityManager를 이용한 Map형식으로 mapping하기

 

Spring boot에서 MySQL JSON 타입 SELECT하는 방법

1. 2018/11/30 - [Develop/Spring Boot] - Spring boot MySQL JSON - MySQL JSON DATA TYPE 값 가져오기

 

 

1. Class를 생성하여 Gson을 이용한 Deserializaion한 JsonString to Object(JsonObject)

 

앞의 1편, 2편, 3편에 사용했던 TestDTO를 수정하자.

 

수정하기 전 먼저 Test_2DTO를 새로 생성한다

public class Test_2DTO { 	private String name; 	private int age; 	 	public Test_2DTO() { 		super(); 	}  	public Test_2DTO(String name, int age) { 		super(); 		this.name = name; 		this.age = age; 	}  	public String getName() { 		return name; 	}  	public void setName(String name) { 		this.name = name; 	}  	public int getAge() { 		return age; 	}  	public void setAge(int age) { 		this.age = age; 	} } 
public class TestDTO {  	private Integer id; 	private String password; 	private List details; 	 	 	public TestDTO() { 		super(); 	}   	public TestDTO(Integer id, String password, List details) { 		super(); 		this.id = id; 		this.password = password; 		this.details = details; 	}   	public Integer getId() { 		return id; 	}   	public void setId(Integer id) { 		this.id = id; 	}   	public String getPassword() { 		return password; 	}   	public void setPassword(String password) { 		this.password = password; 	}   	public List getDetails() { 		return details; 	}   	public void setDetails(List details) { 		this.details = details; 	}   	@Override 	public String toString() { 		return new Gson().toJson(this); 	} } 

 

생성했다면, 

 

public void test() { 		 		String jsonString = "{\r\n" +  				"    \"id\": 1,\r\n" +  				"    \"password\": \"1234\",\r\n" +  				"    \"details\": [\r\n" +  				"        {\r\n" +  				"            \"name\": \"test\",\r\n" +  				"            \"age\": 20\r\n" +  				"        },{\r\n" +  				"            \"name\": \"test2\",\r\n" +  				"            \"age\": 21\r\n" +  				"        }\r\n" +  				"    ] \r\n" +  				"}"; 		Gson gson = new Gson(); 		TestDTO t = gson.fromJson(jsonString, TestDTO.class); 		System.out.println("id : " +t.getId()); 		System.out.println("password : "+t.getPassword()); 		System.out.println("name1 : "+t.getDetails().get(0).getName()); 		System.out.println("age1: "+t.getDetails().get(0).getAge()); 		System.out.println("name2 : "+t.getDetails().get(1).getName()); 		System.out.println("age2: "+t.getDetails().get(1).getAge()); 		 	} 

위에 사용한 Json내용이다., 

 

{     "id": 1,     "password": "1234",     "details": [         {             "name": "test",             "age": 20         },{             "name": "test2",             "age": 21         }     ]  }

 

위 test() 메소드를 실행하면 아래와 같이 Deserializaion한 JsonString이 파싱되어 JsonObject에 알맞게 들어간다.

 

 

2. Jackson의 ObjectMapper를 이용한 Json String to JsonObject 이다.

 

Json내용은 위와 동일한 상태에서 진행하였다.

 

public void test() { 		ObjectMapper objectMapper = new ObjectMapper(); 		  		String jsonString = "{\r\n" +  				"    \"id\": 1,\r\n" +  				"    \"password\": \"1234\",\r\n" +  				"    \"details\": [\r\n" +  				"        {\r\n" +  				"            \"name\": \"test\",\r\n" +  				"            \"age\": 20\r\n" +  				"        },{\r\n" +  				"            \"name\": \"test2\",\r\n" +  				"            \"age\": 21\r\n" +  				"        }\r\n" +  				"    ] \r\n" +  				"}"; 		  try { 	            TestDTO t = objectMapper.readValue(jsonString, TestDTO.class);    // String to Object로 변환 	            System.out.println("ObjectMapper테스트"); 	    		System.out.println("id : " +t.getId()); 	    		System.out.println("password : "+t.getPassword()); 	    		System.out.println("name1 : "+t.getDetails().get(0).getName()); 	    		System.out.println("age1: "+t.getDetails().get(0).getAge()); 	    		System.out.println("name2 : "+t.getDetails().get(1).getName()); 	    		System.out.println("age2: "+t.getDetails().get(1).getAge());	      	 	        } catch (IOException e) { 	            e.printStackTrace(); 	        }		 } 

gson과 마찬가지로 잘 작동된다.

반응형

3. Jackson JsonNode 를 이용한 Deserializaion String to JsonObject

 

어떻게 보면 가장 핵심인 부분일 수도 있다. 클래스 생성없이 할 수 있다는 큰 장점이있다.

 

Deserializaion Json Data는 위와 동일한 데이터를 사용한다.

 

 

public void test() { 		ObjectMapper objectMapper = new ObjectMapper();  		String jsonString = "{\r\n" + "    \"id\": 1,\r\n" + "    \"password\": \"1234\",\r\n" 				+ "    \"details\": [\r\n" + "        {\r\n" + "            \"name\": \"test\",\r\n" 				+ "            \"age\": 20\r\n" + "        },{\r\n" + "            \"name\": \"test2\",\r\n" 				+ "            \"age\": 21\r\n" + "        }\r\n" + "    ] \r\n" + "}"; 		try { 			System.out.println("Jackson JsonNode 테스트"); 			JsonNode t = objectMapper.readValue(jsonString, JsonNode.class); // String to Object로 변환 			 			JsonNode id = t.get("id"); 			System.out.println("id : " + id.asInt()); 			 			JsonNode password = t.get("password"); 			System.out.println("password : " + password.asText()); 			 			JsonNode details = t.get("details"); 			JsonNode details_1 = details.get(0);		 			System.out.println("name1 : " + details_1.get("name").asText()); 			System.out.println("age1: " + details_1.get("age").asInt()); 			 			JsonNode details_2 = details.get(1);	 			System.out.println("name2 : " + details_2.get("name").asText()); 			System.out.println("age2: " + details_2.get("name").asText());  		} catch (IOException e) { 			e.printStackTrace(); 		} } 

class 생성없이 파싱이 잘 되었다

 

이 처럼 웬만한 것들은 class를 생성하여 모든 Deserializaion을 파싱할 수 있으며,

Jackson JsonNode 를 이용하여 처리할 수 있다. 

반응형
반응형

 

Spring Boot에서 Json 파싱을 위해 Jackson을 기본적으로 제공해준다. Spring에서는 maven 또는 gradle을 xml에 추가해야한다.

사실 기본적인 기능은 앞선 gson과 다를게 없다.

 

Spring boot Json 1편, 2편, 4편, 마지막

1. 2018/11/06 - [Spring Boot] - Spring Boot Json, JsonObject로 만들기 - JSON 1편

2. 2018/11/07 - [Develop/Spring Boot] - Spring Boot Json, Gson을 이용한 JsonObject to String, String to JsonObject- JSON 2편

3. 2018/11/12 - [Develop/Spring Boot] - Spring Boot Deserialization Json, Deserialization JsonString to JsonObject - Json 4편

4. 2018/11/13 - [Develop/Spring Boot] - Spring Boot Json, hashmap to json , JsonObject 만들기- JSON 마지막

 

 

 

번외 Database의 값을 Json으로 select하는 방법.

1. 2018/10/24 - [Spring Boot] - Spring boot jpa map, hashmap, JSON형식

2. 2018/10/28 - [Spring Boot] - Spring boot JPA EntityManager를 이용한 Map형식으로 mapping하기

 

Spring boot에서 MySQL JSON 타입 SELECT하는 방법

1. 2018/11/30 - [Develop/Spring Boot] - Spring boot MySQL JSON - MySQL JSON DATA TYPE 값 가져오기

 

 

1. Jackson ObjectMapper (JsonString to Object)

 

public void test() { 		ObjectMapper objectMapper = new ObjectMapper();  		String Json = 		    "{ \"id\" : 1, \"password\" : \"1234\" }";  		try { 		    TestDTO t = objectMapper.readValue(Json, TestDTO.class);	// String to Object로 변환  		    System.out.println("id = " + t.getId()); 		    System.out.println("password = " + t.getPassword()); 		     		    String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(t); //다시 jsonString으로 변환 		    System.out.println(jsonString); 		} catch (IOException e) { 		    e.printStackTrace(); 		} }

 

(위의 TestDTO은 1편에 나와있다.)

 

objectMapper를 통해 JsonString을 Object로 변환할 수 있었고 writeValueAsString을 통해 다시 JsonString으로도 변환이 가능하다

반응형

2. Object From JsonFile

 

 

ObjectMapper objectMapper = new ObjectMapper();  URL url = new URL("file:data/test.json");  TestDTO t = objectMapper.readValue(url, TestDTO.class); 

 

test.json 파일엔

{

"id" : 1,

"password" : 1234

}

들어 가있다.

 

 

기본적인 사용방법은 여기까지이다 다음편에 Jackson JsonNodeClass를 설명한다.

Jackson 가이드 - https://www.baeldung.com/jackson

반응형
반응형

 

1편에서 Spring Boot에서 데이터를 JSON형식으로 표현하는 가장 기본적인 방법인 클래스를 이용한 방법을 배웠다.

이번에는 Gson을 이용한 JsonOjbect to String, String to JsonObject를 알아아보자.

 

개인적인 경험으론 Gson이 가장 Json파싱에서 핵심이 아닐까 생각한다.

 

 

Spring boot Json 1편, 3편, 4편, 마지막

1. 2018/11/06 - [Spring Boot] - Spring Boot Json, JsonObject로 만들기 - JSON 1편

2 .2018/11/09 - [Develop/Spring Boot] - Spring Boot Json, Jackson을 이용한 JsonParsing - Json 3편

3. 2018/11/12 - [Develop/Spring Boot] - Spring Boot Deserialization Json, Deserialization JsonString to JsonObject - Json 4편

4. 2018/11/13 - [Develop/Spring Boot] - Spring Boot Json, hashmap to json , JsonObject 만들기- JSON 마지막

 

 

번외 Database의 값을 Json으로 select하는 방법.

1. 2018/10/24 - [Spring Boot] - Spring boot jpa map, hashmap, JSON형식

2. 2018/10/28 - [Spring Boot] - Spring boot JPA EntityManager를 이용한 Map형식으로 mapping하기

 

Spring boot에서 MySQL JSON 타입 SELECT하는 방법

1. 2018/11/30 - [Develop/Spring Boot] - Spring boot MySQL JSON - MySQL JSON DATA TYPE 값 가져오기

 

 

 

1. 먼저 pom.xml에 의존성을 추가한다.

 

 		com.google.code.gson 		gson 		2.8.5  

 

2. Gson을 이용한 Json 생성

 

public String test3() { 		 		Gson gson = new Gson(); 		JsonObject obj = new JsonObject(); 		String id=null; 		obj.addProperty("id", id); 		obj.addProperty("pass", 1234); 		 		String i = obj.toString(); 		String j = gson.toJson(obj); 		System.out.println(i); 		System.out.println(j); 		return i; } 

 

Gson의 JsonObject를 Import받고 JsonObject를 이용하여 Json 형식으로 만들었다.

위의 toString()으로 호출한 결과와 gson.toJson()을 이용한 결과가 다르다는 걸 볼 수 있다.

아래의 gson.toJson()을 이용하면 null값이 들어올 경우 키값이 사라져 버린다.

 

3. String to JsonObject

 

public void test3() { 		 		Gson gson = new Gson(); 		String json = "{\"id\": 1, \"password\": \"1234\"}";  		TestDTO test = gson.fromJson(json, TestDTO.class); 		System.out.println(test.getId()); 		System.out.println(test.getPassword()); 		 } 

 

1편에서 사용한 TestDTO를 통해 Json객체를 생성할 수 있다.

반응형

4.  객체를 Json으로 만들기

 

	public void test3() { 		 		Gson gson = new Gson(); 		TestDTO test2 = new TestDTO(); 		test2.setId(2); 		test2.setPassword("2222"); 		String i=gson.toJson(test2); 		System.out.println(i); 	} 

 

5.  Gson의 JsonParser와 JsonElement를 통한 JsonParsing

 

	public void test3() { 		 		String json = "{\"id\": 1, \"password\": \"1234\"}"; 		JsonParser jp = new JsonParser(); 		JsonElement je = jp.parse(json); 		int id = je.getAsJsonObject().get("id").getAsInt(); 		String pass = je.getAsJsonObject().get("password").getAsString(); 		System.out.println(id + " / " + pass); 	} 

 

6. Gson을 이용하여 Class의 toString() 을 이용한 Json 생성

 

1편의 TestDTO클래스에 Gson을 이용한 toString() 으로 보다 빠르고 편리하게 Json을 생성할 수 있다.

 

import com.google.gson.Gson;  public class TestDTO {  	private Integer id; 	private String password; 	 	 	public TestDTO() { 		super(); 	} 	public TestDTO(Integer id, String password) { 		super(); 		this.id = id; 		this.password = password; 	} 	public Integer getId() { 		return id; 	} 	public void setId(Integer id) { 		this.id = id; 	} 	public String getPassword() { 		return password; 	} 	public void setPassword(String password) { 		this.password = password; 	} 	 	@Override 	public String toString() { 		return new Gson().toJson(this); 	} }  	public void test3() {  		Gson gson = new Gson(); 		TestDTO test2 = new TestDTO(); 		test2.setId(2); 		test2.setPassword("2222"); 		String json = test2.toString(); 		System.out.println(json); 	} 

 

7. 기타

 

이외에도 Json 예쁘게 출력하는 방법 등 여러가지 기능이 존재한다.

 

 

Gson가이드 - https://github.com/google/gson/blob/master/UserGuide.md

 

반응형
반응형

 

Spring Boot에서 데이터를 JSON형식으로 표현하는 가장 기본적인 방법으로는 클래스를 이용하는 방법이다.

이 방법을 알아야 다음에 Deserialization한 JSON을 만들 수 있다.

 

Spring boot Json 2편, 3편, 4편, 마지막

1. 2018/11/07 - [Develop/Spring Boot] - Spring Boot Json, Gson을 이용한 JsonObject to String, String to JsonObject- JSON 2편

2. 2018/11/09 - [Develop/Spring Boot] - Spring Boot Json, Jackson을 이용한 JsonParsing - Json 3편

3. 2018/11/12 - [Develop/Spring Boot] - Spring Boot Deserialization Json, Deserialization JsonString to JsonObject - Json 4편

4. 2018/11/13 - [Develop/Spring Boot] - Spring Boot Json, hashmap to json , JsonObject 만들기- JSON 마지막

 

번외 Database의 값을 Json으로 select하는 방법.

1. 2018/10/24 - [Spring Boot] - Spring boot jpa map, hashmap, JSON형식

2. 2018/10/28 - [Spring Boot] - Spring boot JPA EntityManager를 이용한 Map형식으로 mapping하기

 

Spring boot에서 MySQL JSON 타입 SELECT하는 방법

1. 2018/11/30 - [Develop/Spring Boot] - Spring boot MySQL JSON - MySQL JSON DATA TYPE 값 가져오기

 

 

 

먼저 DTO를 생성한다.

public class TestDTO {  	private Integer id; 	private String password; 	 	 	public TestDTO() { 		super(); 	} 	public TestDTO(Integer id, String password) { 		super(); 		this.id = id; 		this.password = password; 	} 	public Integer getId() { 		return id; 	} 	public void setId(Integer id) { 		this.id = id; 	} 	public String getPassword() { 		return password; 	} 	public void setPassword(String password) { 		this.password = password; 	} 	 } 

다음 컨트롤러를 하나 생성해준다.

@RestController @RequestMapping(value = "/jsontest") public class TestClass { 	 	@GetMapping() 	public TestDTO test() { 		TestDTO test = new TestDTO(1, "1111"); 		return test; 	} 	 	@GetMapping("/2") 	public List test2() { 		List test = new ArrayList(); 		test.add(0, new TestDTO(1, "1111")); 		test.add(1, new TestDTO(2, "2222")); 		test.add(2, new TestDTO(3, "3333")); 		return test; 	} }
반응형

그리고 실행하게 되면

 

1. test() 실행화면

 

2. test2() 실행화면

 

이렇게 Json 형태로 출력된다

참고로 Map은 Json형태로 출력되지 않고 {"id" = 1, "password"="1111"} 형식으로 출력된다. List만 Json형식으로 출력된다.

또한, 이렇게 클래스로 만든 JsonObject는 Return할 때만 Json으로 출력되지, log또는 print할 경우엔 Json형식으로 출력되지 않는다.

Json형식으로 출력되게 하려면 다음에 할 2편을 참고.

 

기초는 마무리.

 

반응형
반응형


파이썬에서 beautiful soup과 같은 기능을하는 Jsoup라는 것이 있다.

Html을 파싱하는 것이고




	org.jsoup
	jsoup
	1.11.3

xml에 dependency를 추가하고



Jsoup.parse("내용").body().text();

이렇게 사용하면 각종 html코드들을 삭제한 순수 text들이 파싱된다.


기타 사용법은 라이브러리 사이트에서 확인할 수 있다

https://jsoup.org/


반응형
반응형

Spring Boot 에서 TimeZone 설정하려면 아래와 같이 @PostConStruct를 설정해주면 된다.

 

 @SpringBootApplication public class Application {  	@PostConstruct 	void started() { 		TimeZone.setDefault(TimeZone.getTimeZone("Asia/Seoul")); 	}  	public static void main(String[] args) { 		SpringApplication.run(Application.class, args);  	}  } 
반응형

UTC를 원한다면 TimeZone.getTimeZone("UTC")라고 하면 된다.

 

시간을 KST로 설정하고싶어서 TimeZone.getTimeZone("KST")라고 계속 했는데 안되서 삽질한 경험이 있다. KST라고하면 안되고

한국 시간 설정은 Asia/Seoul로 설정해주면 된다.

 

그 외 example timezone offset은 아래의 사이트에서 확인할 수 있다.

https://docs.oracle.com/javase/tutorial/datetime/iso/timezones.html

반응형
반응형


※ RDS사용시 MySQL 한글로 설정 https://pangyeon.tistory.com/9?category=682580


Spring Boot에서 데이터베이스가 UTF8로 설정 되어있음에도 불구하고 물음표(?)로 값이 들어갈 때가 있다.

이 경우 application.propertise에서 mysql 주소뒤에 

주소/테이블명/?useUnicode=true&characterEncoding=utf8


이렇게 붙여주면 데이터 입력시 한글로 잘 들어간다.

반응형

+ Recent posts