Programming/JAVA2014. 4. 17. 21:01

1. pom.xml 

https://code.google.com/p/json-simple/

http://mvnrepository.com/artifact/net.minidev/json-smart

<dependency>
    <groupId>net.minidev</groupId>
    <artifactId>json-smart</artifactId>
    <version>2.0-RC3</version>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>


2. TEST 코드

import java.util.logging.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
//import net.minidev.json.JSONObject;
//import net.minidev.json.parser.JSONParser;
//import net.minidev.json.parser.ParseException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class test {
    Logger logger = Logger.getLogger("xxx");
    
    @RequestMapping("/test")
    public String tests() {
        
        //JSON => String
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value1", 1111);
        jsonObj.put("value2", 2222);
        jsonObj.put("value3", 3333);
        logger.info( "Info : "+jsonObj.toString());
        
        //String => JSON 
        String jsonString = jsonObj.toString();
        JSONParser parser = new JSONParser();
        try {
            Object obj = parser.parse(jsonString);
            jsonObj = (JSONObject) obj;
            logger.info( "Info : "+jsonObj.get("value1"));
            logger.info( "Info : "+jsonObj.get("value2"));
            logger.info( "Info : "+jsonObj.get("value3"));
        }catch ( ParseException e ){
            
        }
        
        return "test";
        
    }
}

==============결과=====================================

정보: Info : {"value3":3333,"value1":1111,"value2":2222}

정보: Info : 1111

정보: Info : 2222

정보: Info : 3333

=======================================================


3. String JSONObject 좀더 간단하게

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>



import java.util.logging.Logger;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class test {
    Logger logger = Logger.getLogger("xxx");
    
    @RequestMapping("/test")
    public String tests() {
        
        //String => JSON 
        String jsonString = "{\"value3\":3333,\"value1\":1111,\"value2\":2222}";
        JSONObject jsonObj = new JSONObject(jsonString);
        logger.info( "Info : "+jsonObj.get("value1"));
        logger.info( "Info : "+jsonObj.get("value2"));
        logger.info( "Info : "+jsonObj.get("value3"));
        return "test";
        
    }
}
Posted by 시니^^