[Java] Json ๋ค๋ฃจ๊ธฐ
์๋ฐ์๋ ๊ธฐ๋ณธ์ ์ผ๋ก json์ด ์ ๊ณต๋์ง ์๋๋ค.
๋๋ฌธ์ ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ๋ก๊ฒจ์จ์ผ ํ๋๋ฐ, ๊ฐ์ค์์ ์ ์ผ ๋์๊ฒ ๊ตฌ๊ธ์์ ๋ง๋ Gson์ด๋ผ๊ณ ํ๋ค.
jar ๋ค์ด๋ก๋
https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.5
๋ ํผ๋ฐ์ค
https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5
์ฌํผ, ์ด๊ฑธ ๋ก๊ฒจ์จ๋ Json์ ์ฐ๋๊ฒ ๊ฝค ๊น๋ค๋ก์ ๋ค.
์๋๋ python ์๋ฒ์์ ๋ณด๋ด๋ json์ ๋ฐ์ ์ฒ๋ฆฌํ๋ ํด๋ผ์ด์ธํธ ์์ค๋ค.
์์ ํฌ์คํ
ํ๋ Python Json ๊ธ์์ ์ด์ด์ง๋ค.
import java.net.*;
import java.io.*;
import com.google.gson.*;
import com.google.gson.stream.*;
//๋ณํ์ ์ํ ์ค์ ํ์
.
//Js, Python๊ณผ ๋ฌ๋ฆฌ ๋์ ํ์
์ด ์ง์๋์ง ์๊ธฐ ๋๋ฌธ์ ํ์ํจ.
class Person
{
public String name;
public String age;
public String[] family;
}
public class Main
{
final static String server_address = "์๋ฒ ์์ดํผ";
final static int port = 12345;
public static void main(String[] args)
{
try
{
//์ฐ๊ฒฐ ํ ์ฝ์ด์ด
var socket = new Socket(server_address, port);
var socket_reader = socket.getInputStream();
var buffer = new byte[1000];
socket_reader.read(buffer, 0, 1000);
var json_string = new String(buffer, "UTF-8");
System.out.println(json_string); //ํ์ธ
var json_reader = new JsonReader(new StringReader(json_string)); //String์ผ๋ก ๋ฐ๋ก ๋ณด๋ด๋๊ฒ๋ ์๋๋ฐ ๊ทธ๊ฑฐ ์ฐ๋ฉด ์๋ฌ๋จ. ๋ฎ์ด์ค์ผ ํจ.
Person result = new Gson().fromJson(json_reader, Person.class); //Person ํ์
์ผ๋ก ์ค์ฒดํ. ๋ณ์์ ํ์
๋ช
์ ํ์
System.out.println(result.family[1]); //ํ์ธ
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

์ฌ๊ธฐ์๋ Person์ด๋ผ๋ ๋ช
ํํ ํ์
์ผ๋ก ์ค์ฒดํ๋ฅผ ํ๋๋ฐ, Json์ ๋์ ํ์
์ ๋ง๊ฒ ์ถ์ํ๋ ํ์
์ธ JsonObject๋ก ๋ณํํด์ ์ธ ์๋ ์๋ค.
new JsonParser().parse(json๋ฌธ์์ด).getAsJsonObject()...
๋์ ์ด๋์ ๋ช
ํํ ํ์
์ ์์๋ด์ง ๋ชปํ๊ธฐ ๋๋ฌธ์ ์์๋ฅผ getํ ๋๋ง๋ค ํ์
๋ช
์๋ฅผ ํด์ค์ผํ๋ค.
์ด JsonObject๋ผ๋ ๋์ ํ๋ฒ ์ฒ์๋ถํฐ ์์ฑ์ ํด๋ณด์
import com.google.gson.*;
import com.google.gson.stream.*;
public class Main
{
public static void main(String[] args)
{
try
{
var json = new JsonObject();
json.addProperty("name", "๊ฒฝ์ง");
json.addProperty("age", 65536);
json.addProperty("nation","korea");
System.out.println(json.toString());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

JsonObject์ ๋ค๋ฅธ JsonObject๋ฅผ ๋ผ์๋ฃ์ ์๋ ์๋ค. ์ด๊ฒ๋ง ๋ฉ์๋ ์ด๋ฆ์ด ๋ค๋ฅด๋ค. add.
import com.google.gson.*;
import com.google.gson.stream.*;
public class Main
{
public static void main(String[] args)
{
try
{
var json = new JsonObject();
json.addProperty("name", "๊ฒฝ์ง");
json.addProperty("age", 65536);
json.addProperty("nation","korea");
var child = new JsonObject();
child.addProperty("์ผ์์", "์๋");
child.addProperty("๋ด ๋ค๋ฅผ", "๋ฐ๋ฆฌ์คํ");
//์ด์ด๋ถ์ด๊ธฐO
json.add("child",child);
System.out.println(json.toString());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

์์๋ฅผ ๊ฐ์ ธ์ค๋ ค๋ฉด ์์ ์ธ๊ธํ๋ฏ์ด ๊ณ์ ํ์ ๋ช ์๋ฅผ ํด์ค์ผ ํ๋ค.
์ด๋ ๊ฒ