๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Java

[Java] JSON ํŒŒ์‹ฑํ•˜๊ธฐ

by cheezzz 2021. 12. 7.
๋ฐ˜์‘ํ˜•

- JAVA์—์„œ JSON ํŒŒ์‹ฑํ•˜๊ธฐ
JSONParser : https://javaee.github.io/javaee-spec/javadocs/javax/json/stream/JsonParser.html
JSONObject : https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html

 

JsonObject (Java(TM) EE 7 Specification APIs)

JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs). It also provides unmodifiable map view to the JSON object name/value mappings. A JsonObject instance can be created from an input source

docs.oracle.com

 

JsonParser (Java(TM) EE 8 Specification APIs)

skipObject default void skipObject() Advance the parser to END_OBJECT. If the parser is in object context, i.e. it has previously encountered a START_OBJECT without encountering the corresponding END_OBJECT, the parser is advanced to the corresponding EN

javaee.github.io


1.
json-simple.jar ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๋‹ค์šด๋กœ๋“œ & ์„ค์ •
๋‹ค์šด๋กœ๋“œ ์ฃผ์†Œ : https://code.google.com/archive/p/json-simple/downloads

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

 

2. ์ฝ”๋“œ ๊ตฌํ˜„

// {"Json1":"test1","Json2":"test2"}
String testTxt = "{\"Json1\":\"test1\",\"Json2\":\"test2\"}";

JSONParser parser = new JSONParser();
JSONObject jsonObj = null;

try{
    jsonObj = (JSONObject) parser.parse(testTxt);
    
    String str1 = (String)jsonObj.get("Json1");
    String str2 = (String)jsonObj.get("Json2");
    
    System.out.println("Json1 : " + str1);
    System.out.println("Json2 : " + str2);
    
}catch(ParseException e){
    // ๋ณ€ํ™˜์‹คํŒจ
    System.out.println("JSON parsing failed !");
    e.printStackTrace();
}


get ์ด์šฉ์‹œ, ์ž…๋ ฅ ๋ณ€์ˆ˜ key ๊ฐ’์˜ value ๊ฐ’์„ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค.

์•„๋ž˜์™€ ๊ฐ™์€ ๊ฒฐ๊ณผ๊ฐ€ ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.

Json1 : test1
Json2 : test2
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€