티스토리 뷰

728x90

출처 : How to convert Java object to / from JSON (Jackson) - Mkyong
스프링3(Spring3) - @ResponseBody + jackson을 이용하여 심플하게 구현하기
Chapter16. 스프링 MVC로 REST API 사용하기 · Spring Study Group
Spring에서 JSON과 연동방법 - 와이케이의 마구잡이 - GitHub Pages
[ERROR:] cvc-complex-type.2.1: Element 'mvc ... - kkan's - Tistory

pom.xml 내용 추가

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.13</version>
		</dependency>

VO 객체

package com.myhome.dto;

import java.util.ArrayList;

public class JSONTest {
	
	private int id;
	private String txt;
	private ArrayList<String> list;
	private String[] arr;

	public String[] getArr() {
		return arr;
	}

	public void setArr(String[] arr) {
		this.arr = arr;
	}

	public ArrayList<String> getList() {
		return list;
	}

	public void setList(ArrayList<String> list) {
		this.list = list;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTxt() {
		return txt;
	}

	public void setTxt(String txt) {
		this.txt = txt;
	}
}

Controller

package com.myhome.ui;

import java.io.IOException;
import java.util.ArrayList;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myhome.dto.JSONTest;

@Controller
public class HelloController {

	@RequestMapping(value = "/jsonTest.do", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody String jsonTest() throws JsonGenerationException, JsonMappingException, IOException {
		
		// 가상의 배열및 리스트에 데이터 add
		ArrayList<String> arraylist = new ArrayList<String>();
		arraylist.add("a");
		arraylist.add("b");
		String[] array = { "a", "b", "c" };

		// VO객체에 SET한후 vo객체자체를 return
		JSONTest test = new JSONTest();
		test.setId(1);
		test.setTxt("textTxt");
		test.setList(arraylist);
		test.setArr(array);
		
		ObjectMapper mapper = new ObjectMapper();
		String jsonString = mapper.writeValueAsString(test);
		
		return jsonString;
	}
}

실행

댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함