Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Workbench
- #코린이 #코딩 #할 수 있다
- 최단거리
- 인스타
- 자료구조
- python기본
- 5장
- Git
- c언어 기본
- 파이썬 알고리즘 인터뷰
- 참고X
- 4장
- git오류
- python기초
- 스택
- c언어
- c언어 제어문
- 데베시 1주차
- 인텔리제이
- 1주차(1)
- git 오류
- 운체 1주차
- 백준
- python자료형
- 도커
- 코딩테스트
- 그리디
- git기초
- 코테
- DP
Archives
- Today
- Total
하루살이 개발자
json 파싱하기 본문
의존성
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1'
compileOnly 'org.projectlombok:lombok:1.16.20'
implementation 'com.google.code.gson:gson:2.8.7'
// https://mvnrepository.com/artifact/org.json/json
implementation group: 'org.json', name: 'json', version: '20210307'
}
package javaAPI.test0;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import javaAPI.gitTest.JavaJjangPostHandler;
import java.io.IOException;
import java.net.InetSocketAddress;
public class JavaServer {
private Integer port = 5678;
private HttpServer server = null;
public JavaServer() throws IOException {
server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/", new MyHandler());
server.createContext("/sum", new MyHandler3());
server.createContext("/user", new MyHandler4());
server.setExecutor(null);
server.start();
System.out.println("server started on port " + port);
}
}
Main
package javaAPI.test0;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
JavaServer server = new JavaServer();
/*
int port = 5678;
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
System.out.println("server started on port " + port);
*/
}
}
package javaAPI.test0;
import com.google.gson.Gson;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.io.OutputStream;
import org.json.simple.JSONObject;
/**
* 요구사항 1.
* 클라이언트가 "/" , "content-type, json " 요청을 보낼때
* API 서버를 하나 5678포트로 생성해서
* json 형태로 "message" : "server check" 를 담아주는 요구사항
*/
public class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
Gson gson = new Gson();
String response = "";
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", "server check");
exchange.getResponseHeaders().add("Content-Type", "application/json"); // 응답 헤더 설정
exchange.sendResponseHeaders(200, response.getBytes().length); // 응답 코드와 길이 설정
// jsonObject을 json 문자열로 변환
String jsonStr = gson.toJson(jsonObject);
// 생성된 json 문자열 출력
System.out.println(jsonStr);
OutputStream os = exchange.getResponseBody();
os.write(jsonStr.getBytes());
os.close();
}
}
package javaAPI.test0;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.json.simple.JSONArray;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Set;
/**
* 이미 있는 JSON 파일 파싱하기
*/
public class MyHandler2 implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
System.out.println("MyHandler2 call..");
Gson gson = new Gson();
// FileReader 생성
String path = MyHandler2.class.getResource("").getPath();
System.out.println("path :" + path);
/*
// json파일 읽어서, User 객체로 변환
System.out.println("성공?");
Gson gson = new Gson();
User user = gson.fromJson(fileReader, User.class);
// User 객체 출력 및 post_count의 총합 구하기
System.out.println(user);
*/
//
String filePath = "/Users/gimhwigyeong/Desktop/hwi/project/javaAPI/src/main/java/javaAPI/test0/user.json";
try {
JsonReader jsonReader = new JsonReader(new FileReader(filePath));
JsonObject object = gson.fromJson(jsonReader, JsonObject.class);
System.out.println("\"user_id\" : " + object.get("user_id"));
//System.out.println(object.toString());
System.out.println("중간 ===");
Set<Map.Entry<String, JsonElement>> element = object.entrySet();
for(Map.Entry<String, JsonElement> entry : element){
System.out.println("key: " + entry.getKey());
System.out.println("val: " + entry.getValue());
System.out.println("==========================");
}
}catch (Exception e){
System.out.println("error");
e.printStackTrace();
}
}
}
package javaAPI.test0;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.stream.JsonReader;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.json.simple.JSONArray;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;
/**
* 요구사항3
* 이미 있는 JSON 파일 파싱하기2
* - 모든 user의 post_count의 합
*/
public class MyHandler3 implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
System.out.println("MyHandler2 call..");
Gson gson = new Gson();
// FileReader 생성
String path = MyHandler3.class.getResource("").getPath();
System.out.println("path :" + path);
/*
// json파일 읽어서, User 객체로 변환
System.out.println("성공?");
Gson gson = new Gson();
User user = gson.fromJson(fileReader, User.class);
// User 객체 출력 및 post_count의 총합 구하기
System.out.println(user);
*/
//
String filePath = "/Users/gimhwigyeong/Desktop/hwi/project/javaAPI/src/main/java/javaAPI/data/user2.json";
String jsonStr = "";
try {
JsonReader jsonReader = new JsonReader(new FileReader(filePath));
JSONArray jsonArray = gson.fromJson(jsonReader, JSONArray.class);
System.out.println(jsonArray.toString());
System.out.println("size: " + jsonArray.size());
System.out.println("get0: " + jsonArray.get(0));
int sum = 0;
for(int i = 0; i < jsonArray.size(); i++){
JsonObject object = gson.fromJson(jsonArray.get(i).toString(), JsonObject.class);
String user_id = object.get("user_id").getAsString();
String username = object.get("username").getAsString();
String count = object.get("post_count").getAsString();
/*
System.out.println("user_id: " + user_id);
System.out.println("username: " + username);
System.out.println("post_count: " + count);
*/
int post_count = object.get("post_count").getAsInt();
sum += post_count;
}
System.out.println("모든 user의 post_count의 합: " + sum);
JsonObject resultObject = new JsonObject();
resultObject.addProperty("sum", sum);
jsonStr = gson.toJson(resultObject);
exchange.getResponseHeaders().add("Content-Type", "application/json"); // 응답 헤더 설정
exchange.sendResponseHeaders(200, jsonStr.getBytes().length); // 응답 코드와 길이 설정
}catch (Exception e){
System.out.println("error");
exchange.getResponseHeaders().add("Content-Type", "application/json"); // 응답 헤더 설정
exchange.sendResponseHeaders(500, jsonStr.getBytes().length); // 응답 코드와 길이 설정
e.printStackTrace();
}finally {
OutputStream os = exchange.getResponseBody();
os.write(jsonStr.getBytes());
os.close();
}
}
}
package javaAPI.test0;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.stream.JsonReader;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.json.simple.JSONArray;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* 요구사항4
* 이미 있는 JSON 파일 파싱하기
* - User 객체로 변환한 후, 모든 user의 post_count의 합 구하기
*/
public class MyHandler4 implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
System.out.println("MyHandler4 call..");
Gson gson = new Gson();
/*
// json파일 읽어서, User 객체로 변환
System.out.println("성공?");
Gson gson = new Gson();
User user = gson.fromJson(fileReader, User.class);
// User 객체 출력 및 post_count의 총합 구하기
System.out.println(user);
*/
//
String filePath = "/Users/gimhwigyeong/Desktop/hwi/project/javaAPI/src/main/java/javaAPI/data/user2.json";
String jsonStr = "";
try {
JsonReader jsonReader = new JsonReader(new FileReader(filePath));
JSONArray jsonArray = gson.fromJson(jsonReader, JSONArray.class);
System.out.println(jsonArray.toString());
System.out.println("size: " + jsonArray.size());
System.out.println("get0: " + jsonArray.get(0));
int sum = 0;
List<User> userList = new ArrayList<>();
for(int i = 0; i < jsonArray.size(); i++){
//JsonObject object = gson.fromJson(jsonArray.get(i).toString(), JsonObject.class);
User users = gson.fromJson(jsonArray.get(i).toString(), User.class);
int user_id = users.getUser_id();
String username = users.getUsername();
int count = users.getPost_count();
System.out.println("user_id: " + user_id + ", username: " + username);
userList.add(new User(user_id, username, count));
}
for(User user : userList){
sum += user.getPost_count();
}
System.out.println("모든 user의 post_count의 합: " + sum);
JsonObject resultObject = new JsonObject();
resultObject.addProperty("sum", sum);
jsonStr = gson.toJson(resultObject);
exchange.getResponseHeaders().add("Content-Type", "application/json"); // 응답 헤더 설정
exchange.sendResponseHeaders(200, jsonStr.getBytes().length); // 응답 코드와 길이 설정
}catch (Exception e){
System.out.println("error");
exchange.getResponseHeaders().add("Content-Type", "application/json"); // 응답 헤더 설정
exchange.sendResponseHeaders(500, jsonStr.getBytes().length); // 응답 코드와 길이 설정
e.printStackTrace();
}finally {
OutputStream os = exchange.getResponseBody();
os.write(jsonStr.getBytes());
os.close();
}
}
}
package javaAPI.test0;
public class User {
int user_id;
String username;
int post_count;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getPost_count() {
return post_count;
}
public void setPost_count(int post_count) {
this.post_count = post_count;
}
public User(int user_id, String username, int post_count) {
this.user_id = user_id;
this.username = username;
this.post_count = post_count;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("User{");
sb.append("user_id=").append(user_id);
sb.append(", username='").append(username).append('\'');
sb.append(", post_count=").append(post_count);
sb.append('}');
return sb.toString();
}
}
////추가
package javaAPI.gitTest;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
JavaJjangServer server = new JavaJjangServer();
}
}
package javaAPI.gitTest;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
public class JavaJjangServer {
private Integer port = 8000;
private HttpServer server = null;
public JavaJjangServer() throws IOException {
System.out.println("Java JJang Server On! port : 8000");
server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/javajjang", new JavaJjangPostHandler());
server.setExecutor(null);
server.start();
}
}
package javaAPI.gitTest;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JavaJjangPostHandler implements HttpHandler {
// 요청 들어오면 Start
@Override
public void handle(HttpExchange exchange) throws IOException {
System.out.println("JavaJJANG Post Handler-------");
// json으로 입력받음
InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), "utf-8");
BufferedReader br = new BufferedReader(isr);
String query = br.readLine();
System.out.println("쿼리 : \"" + query + "\"");
Integer seed = getSeedFromQuery(query);
System.out.println(seed);
RandomMaker randomMaker = new RandomMaker(seed);
List<Integer> result = randomMaker.getRandomThree();
System.out.println(result.toString());
String response = "{\"result\":\"" + result.toString() + "\"}";
System.out.println(response);
exchange.getResponseHeaders().set("Content-Type", "appication/json");
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
private Integer getSeedFromQuery(String query) throws UnsupportedEncodingException {
Map<String, Object> parameters = new HashMap<>();
System.out.println("query : " + query);
Integer result = 0;
if (query != null) {
String pairs[] = query.split("[&]");
for (String pair : pairs) {
String param[] = pair.split("[=]");
System.out.println("0 : " + param[0]);
System.out.println("1 : " + param[1]);
result = Integer.parseInt(param[1]);
}
return result;
}else return 0;
}
}
package javaAPI.gitTest;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class RandomMaker {
private Integer seed;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RandomMaker that = (RandomMaker) o;
return seed.equals(that.seed);
}
@Override
public int hashCode() {
return Objects.hash(seed);
}
public Integer getSeed() {
return seed;
}
public void setSeed(Integer seed) {
this.seed = seed;
}
public RandomMaker(Integer seed) {
this.seed = seed;
}
public RandomMaker() {this.seed = 0;}
//억지 스트림과 람다를 써 봄
public List<Integer> getRandomThree(){
System.out.println("random maker on!");
List<Integer> result = Stream.iterate(new Random().nextInt(this.seed), x ->{
return new Random().nextInt(this.seed);
}).limit(3).collect(Collectors.toList());
return result;
}
}