반응형

*JSON 파서 구현 개념정리 ( 저장하기 / 불러오기 )

- source 내 Getters and Setters / Constructor using fields  / toString 자동으로 구현해주는 기능 이용.

 

1. Json 미 사용버전

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class Main {
	public static void main(String[] args) {

		Article article = new Article(3, "2020-12-12 12:12:12", "제목", "내용");

		String articleJson = article.toJson();

		String fileName = article.getId() + ".txt";

		// 자바 파일 저장하기
		try {
			OutputStream output = new FileOutputStream(fileName);
			output.write(articleJson.getBytes());
		} catch (Exception e) {
			e.getStackTrace();
		}

		// 자바 파일 불러오기(읽기)
		try {
			String filePath = fileName; // 대상 파일
			FileInputStream fileStream = null; // 파일 스트림

			fileStream = new FileInputStream(filePath);

			byte[] readBuffer = new byte[fileStream.available()];
			while (fileStream.read(readBuffer) != -1) {
			}
	
			String rs = new String(readBuffer);
			Article article2 = new Article();
			article2.applyJson(rs);
	
			
			System.out.println(article2);

			fileStream.close(); // 스트림 닫기
		} catch (Exception e) {
			e.getStackTrace();
		}

	}
}

// 모든 객체의 부모는 Object
class Article extends Object {
	// 실무에서 아래 변수들은 private로 진행(외부에서 접근 불가)
	private int id;
	private String regDate;
	private String title;
	private String body;

	@Override
	public String toString() {
		return "Article [id=" + id + ", regDate=" + regDate + ", title=" + title + ", body=" + body + "]";
	}

	public void applyJson(String rs) {

		rs = rs.replace("{", "");
		rs = rs.replace("}", "");
		String[] bits = rs.split(",");

		for (int i = 0; i < bits.length; i++) {
			String[] fieldBits = bits[i].split(":");

			String fieldName = fieldBits[0];

			fieldName = fieldName.replace("\"", "");

			String fieldValue = fieldBits[1];

			if (fieldName.equals("id")) {
				this.id = (Integer.parseInt(fieldValue));
			} else if (fieldName.equals("regDate")) {
				this.regDate = fieldValue;
			} else if (fieldName.equals("title")) {
				this.title = fieldValue;
			} else if (fieldName.equals("body")) {
				this.body = fieldValue;
			}

		}
	}

	public Article() {

	}

	public Article(int id, String regDate, String title, String body) {
		super();
		this.id = id;
		this.regDate = regDate;
		this.title = title;
		this.body = body;
	}

	public String toJson() {
		String rs = String.format("{\"id\":%d,\"regDate\":%s,\"title\":%s,\"body\":%s}", id, regDate, title,
				body);
		return rs;
	}

	// private 변수 접근을 위해 getter, setter 사용
	public int getId() {
		return id;
	}

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

	public String getRegDate() {
		return regDate;
	}

	public void setRegDate(String regDate) {
		this.regDate = regDate;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}
}

 

2. Json 사용 버전

- 자바 파일 저장하기

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
	public static void main(String[] args) {
		
		ObjectMapper mapper = new ObjectMapper();
		
		Article article = new Article(1, "2020-12-12 12:12:12", "제목 \"나그네\" 입니다.", "내용 {}");
		String jsonString = null;
		
		try {
			// mapper한테 일 시키는 것
			jsonString = mapper.writeValueAsString(article);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		
		System.out.println(jsonString);
		
		String fileName = article.id + ".txt";
		
		// 파일 저장
		try {
			mapper.writeValue(new File(fileName), article);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
class Article {
	public int id;
	public String regDate;
	public String title;
	public String body;
	public Article(int id, String regDate, String title, String body) {
		super();
		this.id = id;
		this.regDate = regDate;
		this.title = title;
		this.body = body;
	}
	
	
}

 

- 자바 파일 불러오기(읽기)

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
	public static void main(String[] args) {
		
		ObjectMapper mapper = new ObjectMapper();
		
		Article article = new Article();
		
		// 불러오기
		try {
			article = mapper.readValue(new File("1.txt"), Article.class);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println(article); // article 리모콘이 들어있어서 그냥 출력 시 주소가 나온다. 해결법 > source toString 생성
		
		
		
	}
}
class Article {
	public int id;
	public String regDate;
	public String title;
	public String body;
	public Article(int id, String regDate, String title, String body) {
		this.id = id;
		this.regDate = regDate;
		this.title = title;
		this.body = body;
	}
	
	public Article() {
		
	}

	@Override
	public String toString() {
		return "Article [id=" + id + ", regDate=" + regDate + ", title=" + title + ", body=" + body + "]";
	}	
	
	
}

 

3. Json 사용 버전(저장, 불러오기 합친버전)

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main{
	public static void main(String[] args) {
		
		ObjectMapper mapper = new ObjectMapper();
		
		Article article = new Article(1, "2020-12-12 12:12:12", "제목", "내용");
		
		String jsonString = null;
		
		try {
			jsonString = mapper.writeValueAsString(article);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		
		String fileName = article.id + ".txt";
		
		// 파일 저장하기
		try {
			mapper.writeValue(new File(fileName), article);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Article article2 = new Article();
		
		// 파일 불러오기
		try {
			article2 = mapper.readValue(new File("1.txt"), Article.class);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		System.out.println(article2);
		
		
	}
}

class Article {
	public int id;
	public String regDate;
	public String titile;
	public String body;
	
	public Article(int id, String regDate, String titile, String body) {
		this.id = id;
		this.regDate = regDate;
		this.titile = titile;
		this.body = body;
	}
	
	public Article() {
		
	}

	@Override
	public String toString() {
		return "Article [id=" + id + ", regDate=" + regDate + ", titile=" + titile + ", body=" + body + "]";
	}
	
}
반응형

+ Recent posts