반응형

어찌보면 가장 중요한 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 를 이용하여 처리할 수 있다. 

반응형
반응형

 

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

 

반응형

+ Recent posts