반응형

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

반응형

+ Recent posts