자바2010. 5. 23. 04:00
출처 : http://devkkaok.tistory.com/92 까오기네집

요구사항 
결과값을 json 형태로 반환하기 
 
관련 라이브러리 
- ezmorph-1.0.6.jar
- json-lib-2.3-jdk15.jar
- commons-lang.jar
- commons-logging-1.1.jar
- commons-collections-3.2.jar
- commons-beanutils-1.8.0.jar
- commons-beanutils-bean-collections-1.8.0.jar
- commons-beanutils-core-1.8.0.jar

테스트에 앞서 dto 생성
package test.dto;

import java.math.BigDecimal;
import java.util.Date;

public class A {

    private String id;
    private int age;
    private Date credate;
    private BigDecimal iq;
    
    public A(String id, int age, Date credate, BigDecimal iq){
        this.id=id;
        this.age=age;
        this.credate=credate;
        this.iq=iq;
    }
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Date getCredate() {
        return credate;
    }
    public void setCredate(Date credate) {
        this.credate = credate;
    }
    public BigDecimal getIq() {
        return iq;
    }
    public void setIq(BigDecimal iq) {
        this.iq = iq;
    }

}

실재 처리 할 util 클래스

public class JsonUtil {
    public static String getJsonString(Object obj){
        if(obj == null) return null;
        return JSONObject.fromObject(obj).toString();
    }
}

테스트 클래스 
public class JsonTest {
    public static void main(String[] args) {
        // object test
        System.out.println(JsonUtil.getJsonString(getTestData()));
        // result : {"age":20,"credate":{"date":26,"day":1,"hours":14,"minutes":46,"month":6,"seconds":19,"time":1280123179718,"timezoneOffset":-540,"year":110},"id":"kkaok","iq":2010}
    }

    private static Object getTestData(){
        A a = new A("kkaok", 20, new Date(), new BigDecimal(2010));
        return a;
    }
}

1. 기본 객체 테스트 
result :
{"age":20,"credate":{"date":26,"day":1,"hours":14,"minutes":46,"month":6,"seconds":19,"time":1280123179718,"timezoneOffset":-540,"year":110},"id":"kkaok","iq":2010}

2. java.util.Date type인 경우 conversion하기 
기본적인 테스트는 성공했는데 결과 값 중에 날짜가 영 맘에 안든다. 
날짜를 바꿔보기 ("yyyy-MM-dd HH:mm:ss.SSS")

JsonValueProcessor로 java.util.Date 타입인 경우 "yyyy-MM-dd HH:mm:ss.SSS" 형태로 결과를 보여 주도록 한다. 

package test.support;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;


public class JavaUtilDateJsonValueProcessor implements JsonValueProcessor {
    
    private final DateFormat defaultDateFormat;
    
    public JavaUtilDateJsonValueProcessor(){
        defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.KOREA);
    }
    
    @Override
    public Object processArrayValue(Object paramObject,
            JsonConfig paramJsonConfig) {
        if(paramObject == null) return null;
        return defaultDateFormat.format(paramObject);
    }

    @Override
    public Object processObjectValue(String paramString, Object paramObject,
            JsonConfig paramJsonConfig) {
        return processArrayValue(paramObject, paramJsonConfig);
    }
}


util에 JsonConfig에 추가해 준다. 

public class JsonUtil {
    public static String getJsonString(Object obj){
        if(obj == null) return null;
        JsonValueProcessor beanProcessor = new JavaUtilDateJsonValueProcessor();
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(java.util.Date.class, beanProcessor);        
        return JSONObject.fromObject(obj, jsonConfig).toString();
    }
}

테스트 결과 
{"age":20,"credate":"2010-07-26 14:46:20.406","id":"kkaok","iq":2010}

괜찮게 나온다. 

3. 값이 null일때는 어떻게 나올까?

    public static void main(String[] args) {
        // object test
        System.out.println(JsonUtil.getJsonString(getTestData()));
        // result : {"age":20,"credate":{"date":26,"day":1,"hours":14,"minutes":46,"month":6,"seconds":19,"time":1280123179718,"timezoneOffset":-540,"year":110},"id":"kkaok","iq":2010}
        // 날짜 꼬라지 하고는 바꾸자 
        System.out.println(JsonUtil.getJsonString2(getTestData()));
        // result : {"age":20,"credate":"2010-01-25 17:30:19.165","id":"kkaok","iq":2010}

        // null로 대충 채우고 확인 
        System.out.println(JsonUtil.getJsonString2(getTestData2()));
        // result : {"age":20,"credate":null,"id":"","iq":0}
    }
    
    private static Object getTestData2(){
        A a = new A(null, 20, null, null);
        return a;
    }

결과 : 
{"age":20,"credate":null,"id":"","iq":0}
없으면 없는대로 나온다. 

4. 객체 안에 객체를 필드로 가지고 있는 경우는 어떨까?
dto 추가
package test.dto;

public class B {

    public B(A a, String bid) {
        super();
        this.a = a;
        this.bid = bid;
    }
    private A a;
    private String bid;

    public A getA() {
        return a;
    }
    public void setA(A a) {
        this.a = a;
    }
    public String getBid() {
        return bid;
    }
    public void setBid(String bid) {
        this.bid = bid;
    }
    
}


테스트 
    public static void main(String[] args) {
        // 객체를 필드로 가지고 있는 객체 테스트1 
        System.out.println(JsonUtil.getJsonString2(getTestData3()));
        // result : {"a":{"age":20,"credate":"2010-07-26 14:57:04.468","id":"kkaok","iq":2010},"bid":"aaaa"}
    }
    private static Object getTestData3(){
        A a = new A("kkaok", 20, new Date(), new BigDecimal(2010));
        B b = new B(a, "aaaa");
        return b;
    }


5. Map인 경우는?
    public static void main(String[] args) {
        // map test 
        System.out.println(JsonUtil.getJsonString2(getTestData5()));
        // result : {"credate":"2010-07-26 14:57:04.468","test":{"a":{"age":20,"credate":"2010-07-26 14:57:04.468","id":"kkaok","iq":2010},"bid":"aaaa"},"name":"kkaok"}
    }
    private static Object getTestData5(){
        Map map = new HashMap();
        map.put("test", getTestData3());
        map.put("name", "kkaok");
        map.put("credate", new Date());
        return map;
    }

6. list 테스트.

util에 JSONArray 추가 
public class JsonUtil {

    public static String getJsonString(Object obj){
        if(obj == null) return null;
        return JSONObject.fromObject(obj).toString();
    }

    public static String getJsonString2(Object obj){
        if(obj == null) return null;
        JsonValueProcessor beanProcessor = new JavaUtilDateJsonValueProcessor();
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(java.util.Date.class, beanProcessor);        
        return JSONObject.fromObject(obj, jsonConfig).toString();
    }

    public static String getJSONArrayString(Object objList){
        if(objList == null) return null;
        JSONArray jsonArray = JSONArray.fromObject(objList);
        return jsonArray.toString();
    }
}

테스트
    public static void main(String[] args) {
        // list test 
        System.out.println("6. "+JsonUtil.getJSONArrayString(getTestData6()));
        // result : [{"credate":{"date":26,"day":1,"hours":14,"minutes":57,"month":6,"seconds":4,"time":1280123824468,"timezoneOffset":-540,"year":110},"test":{"a":{"age":20,"credate":{"date":26,"day":1,"hours":14,"minutes":57,"month":6,"seconds":4,"time":1280123824468,"timezoneOffset":-540,"year":110},"id":"kkaok","iq":2010},"bid":"aaaa"},"name":"kkaok"},{"a":{"age":20,"credate":{"date":26,"day":1,"hours":14,"minutes":57,"month":6,"seconds":4,"time":1280123824468,"timezoneOffset":-540,"year":110},"id":"kkaok","iq":2010},"bid":"aaaa"}]
    }
    private static Object getTestData6(){
        List list = new ArrayList();
        list.add(getTestData5());
        list.add(getTestData3());
        return list;
    }

List안에 객체랑 Map이랑 마구 섞어 놓아도 잘 된다. 


7. Map안에 List는 잘 처리 될까?

    public static void main(String[] args) {
        // map 안에 list test 
        System.out.println("7. "+JsonUtil.getJsonString2(getTestData7()));
        // result : {"credate":"2010-07-26 14:57:04.468","test":[{"credate":"2010-07-26 14:57:04.468","test":{"a":{"age":20,"credate":"2010-07-26 14:57:04.468","id":"kkaok","iq":2010},"bid":"aaaa"},"name":"kkaok"},{"a":{"age":20,"credate":"2010-07-26 14:57:04.468","id":"kkaok","iq":2010},"bid":"aaaa"}],"name":"kkaok"}
    }
    private static Object getTestData7(){
        Map map = new HashMap();
        map.put("test", getTestData6());
        map.put("name", "kkaok");
        map.put("credate", new Date());
        return map;
    }
잘 된다. ^^ 

8. List안에 List 담기 

    public static void main(String[] args) {
        // list 안에 list test 
        System.out.println("8. "+JsonUtil.getJSONArrayString(getTestData8()));
        // result : [[{"credate":{"date":26,"day":1,"hours":14,"minutes":57,"month":6,"seconds":4,"time":1280123824468,"timezoneOffset":-540,"year":110},"test":{"a":{"age":20,"credate":{"date":26,"day":1,"hours":14,"minutes":57,"month":6,"seconds":4,"time":1280123824468,"timezoneOffset":-540,"year":110},"id":"kkaok","iq":2010},"bid":"aaaa"},"name":"kkaok"},{"a":{"age":20,"credate":{"date":26,"day":1,"hours":14,"minutes":57,"month":6,"seconds":4,"time":1280123824468,"timezoneOffset":-540,"year":110},"id":"kkaok","iq":2010},"bid":"aaaa"}],{"a":{"age":20,"credate":{"date":26,"day":1,"hours":14,"minutes":57,"month":6,"seconds":4,"time":1280123824468,"timezoneOffset":-540,"year":110},"id":"kkaok","iq":2010},"bid":"aaaa"}]
    }
    private static Object getTestData8(){
        List list = new ArrayList();
        list.add(getTestData6());
        list.add(getTestData3());
        return list;
    }

파싱할때 객체가 isArray 면 JSONArray를 이용하고 그외 나머지는 JSONObject를 이용하면 쉽게 변환이 된다. 
그외 conversion이 필요한 경우 JsonConfig에 등록해서 처리하면 된다. 
값을 처리하는 인터페이스는 JsonValueProcessor 이용하고 Bean을 처리하는 인터페이스는 JsonBeanProcessor 이용하면 된다. 
그외 인터페이스 참고 

'자바' 카테고리의 다른 글

12회 한국 자바 개발자 컨퍼런스  (5) 2012.01.26
객체를 Json 형태로 출력하기  (6) 2010.05.23
제10회 한국자바개발자 컨퍼런스  (0) 2009.02.05
Posted by 양군이당

댓글을 달아 주세요

  1. 아하하.. 삽질하다가 검색해서 좋은정보 얻어 갈께요 =_=ㅋ
    설마설마했는데 양군형 블로그로 오네요ㅋㅋㅋㅋㅋ

    2010.07.29 13:37 신고 [ ADDR : EDIT/ DEL : REPLY ]
  2. 난 그냥 내가 정말 블로그처럼 정말 정말 버전 genious 기사 또는 블로그의 더 많은를 검토 수있는 나중에 돌려 보내 모든 사파리 주위 항목을 책 표시된 사용자 이름 glasscannonz 내부 Jumptag에서 추구를 위해이 사이트를 관찰 게시물!

    2011.10.23 04:26 [ ADDR : EDIT/ DEL : REPLY ]
  3. 지식을 공유하는 것은 재미이다. 당신은 어떻게 생각하십니까? 당신은 무엇을 쓰는 거죠?지식을 공유하는 것은 재미이다. 당신은 어떻게 생각하십니까? 당신은 무엇을 쓰는 거죠?
    http://kaos.web44.net

    2012.01.10 00:01 [ ADDR : EDIT/ DEL : REPLY ]
  4. 송승현

    라이브러리 build 하실 때, json-lib-2.2.2-jdk15.jar 랑 다른것도 해주셧나요??

    저는 안드로이드에서 build 해서 쓸려고 하는데요.

    Json 객체 만들려는데... java.lang.VerifyError: net.sf.json.JSONObject 가 계속 나서요..

    2012.01.11 17:14 [ ADDR : EDIT/ DEL : REPLY ]
  5. 감사합니다. 삽질하다가 좋은정보 얻어가네요^^

    2012.01.18 14:13 [ ADDR : EDIT/ DEL : REPLY ]
  6. 정보가 현명한을위한이 웹사이트는 매우 행복합니다. 이 웹사이트는 한 가지 목표로하고있다지만,이 웹 사이트는 모든 주제와 디자인의 사진을있습니다. 이 블로그를 정말 좋아하고 서비스를 사용하고 있습니다. 본 웹사이트는 당신이 원하는 특정 주제에 대한 정보의 많은 증명입니다. 그 정보는 사실과 특정 주제에 대한 좋은 언어를 사용하고 있습니다. 이 웹사이트에 대단히 감사입니다.

    2012.11.20 05:17 [ ADDR : EDIT/ DEL : REPLY ]

자바/Web2008. 6. 26. 02:26
원문 http://blog.naver.com/forioso/10009590986

1 문서 개요 #

  • 작성일 : 2006/04/04
  • 작성자 : http://www.0bin.net/moniwiki/wiki.php/Specification/OPML?action=download&value=mail.png
  • 문서 내용 : AJAX XMLHTTPREQUEST에서 데이터 교환 형식으로 사용되는 JSON에 대한 정리

2 개요 #

  • Javascript Object Notation.
  • lightweight data 교환 형식.
  • 사람이 읽고 쓰기 쉬움.
  • 기계가 파싱하고 생성하기 쉬움.

3 형식 #

3.1 Object #

  • 중괄호({})로 시작하고 끝남
  • member : 문자열과 값으로 구성되어 있고 콜론(:)으로 구분, 각 멤버들은 콤마(,)로 구분
  • array : 대괄호([])로 시작하고 끝나며 각 값은 콤마(,)로 구분
  • value : 값은 string, number, object, array, true, false, null 사용 가능
  • string : 문자열은 쌍따옴표(")로 둘러 쌓여야 하며 Unicode character 또는 일반적인 escape 문자(\", \\, \/, \b, \f, \n, \r, \t, \u four-hex-digits)를 포함한다.
    oav.gif
    sn.gif

3.2 예시 #

{

"Image": {

"Width":800,

"Height":600,

"Title":"View from 15th Floor",

"Thumbnail":{

"Url":"http:/\/scd.mm-b1.yimg.com\/image\/481989943",

"Height": 125,

"Width": "100"

},

"IDs":[ 116, 943, 234, 38793 ]

}

}
  • 출처 : Yahoo JSON 예제
  • 예제에서 Image는 최상위 object이고 모든 다른 데이터들은 이 object의 멤버.
  • Width, Height, Title는 숫자와 문자열 데이타를 포함하고 있는 기본적인 멤버.
  • Thumbnail은 Url, Height, Width를 멤버로 포함하고 있는 중첩 object.
  • ?IDs는 숫자 값을 가지고 있는 array.
  • Url 문자열 값에서 슬래쉬(/)가 escape 됨에 주의

4 참고 사이트 #

'자바 > Web' 카테고리의 다른 글

드디어 JavaFX 1.0 정식 Release...  (0) 2008.12.09
Eclipse Ganymede 출동~  (0) 2008.07.02
JSON  (0) 2008.06.26
JSON vs XML  (0) 2008.06.26
XML과 JSON 사이에 변환 패턴  (0) 2008.06.26
JavaScript 객체 JSON  (0) 2008.06.26
Posted by 양군이당
TAG JSON

댓글을 달아 주세요

자바/Web2008. 6. 26. 02:21
출처 정원희's blog, season 2006 start! | 딱따구리
원문 http://blog.naver.com/nobodyuknow/100028605773


Pattern XML JSON Access
1
"e": null o.e
2text "e": "text" o.e
3
"e":{"@name": "value"} o.e["@name"]
4text "e": { "@name": "value", "#text": "text" } o.e["@name"] o.e["#text"]
5text text "e": { "a": "text", "b": "text" } o.e.a o.e.b
6text text "e": { "a": ["text", "text"] } o.e.a[0] o.e.a[1]
7text text "e": { "#text": "text", "a": "text" } o.e["#text"] o.e.a

출처 Night Sidunge | 시둥이
원문 http://blog.naver.com/way133/60029787010

출처 : http://cafe.naver.com/webagencyalone.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=25

xml -> json


1. [패턴1]

<?xml version="1.0"  encoding="Shift_JIS" ?>

  <rss>

    <channel>

      <title>111</title>
      <link>222</link>

    </channel>

  </rss>


  json으로 바꾸면...


{


   rss: {
   

     channel: {


        title: "111",
      link: "222"


     }


   }

}


javascript에서 json변수의 요소를 가저올때(json변수명이 data일 경우)

data.rss.channel.title    ---->111  다음과 같이 써도 동일 data["rss"]["channel"]["title"]

data.rss.channel.link    ---->222  다음과 같이 써도 동일 data["rss"]["channel"]["link"]


2.[패턴2]

<?xml version="1.0"  encoding="Shift_JIS" ?>

  <rss>

    <channel>

      <title>111</title>

      <title>222</title>
      <link>333</link>

    </channel>

    <channel>

      <title>444</title>

      <title>555</title>
      <link>666</link>

    </channel>

  </rss>


json으로 바꾸면...


{


  rss: {


    channel: [
{
       


      title: [
          "111",
          "222"
        ],



      link: "333"
     

    },


    {

  
   title: [
          "444",
          "555"
        ],




      link: "666"
      }]



  }

}


data.rss.channel[0].title[0]     --->111  다음과 같이 써도 동일 data["rss"]["channel"][0]["title"][0]

data.rss.channel[1].link         --->666  다음과 같이 써도 동일 data["rss"]["channel"][1]["link"]


3.패턴[3]

<?xml version="1.0"  encoding="Shift_JIS" ?>

  <rss version="2.0">

    <channel>

      <title>111</title>
      <link opt1="opt1111" opt2="opt222">222</link>

    </channel>

  </rss>


json으로 바꾸면...


{
 

  rss: {


    version: "2.0",

    channel: {


      title: "111",

      link: {


        opt1: "opt1111",
        opt2: "opt222",
        "#text": "222"


      }


     }

  }

}


data["rss"]["channel"]["link"]["#text"]   --->222

data.rss.channel.link.#text 로 하면...에러발생...

#가 파싱할때 예약어인거 같음..


4.패턴4

<?xml version="1.0"  encoding="Shift_JIS" ?>
  <rss version="2.0">
    <channel>
      <title aaa="111"/>
      <asdfsdf/>
    </channel>
</rss>


json으로 바꾸면...


{
  rss: {


     version: "2.0",


     channel: {
      title: { aaa: "111" }


     }


   }


 }



5.아래와같이 동일한 옵션명이 있으면 에러

<bb aa="11" aa="22"/>

옵션명에 :를 넣는경우는 xmlns로 정의된경우만 가능...이외에는 에러남...

아래와 같은 경우 옵션명에 :를 넣음

<?xml version="1.0"  encoding="utf-8" ?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Center"/>
   <Borders/>
   <Font ss:FontName="MS Pゴシック" x:CharSet="128" x:Family="Modern" ss:Size="11"/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
</Workbook>

'자바 > Web' 카테고리의 다른 글

JSON  (0) 2008.06.26
JSON vs XML  (0) 2008.06.26
XML과 JSON 사이에 변환 패턴  (0) 2008.06.26
JavaScript 객체 JSON  (0) 2008.06.26
Java 객체를 이용해서 JSON객체를 위한 텍스트 생성하기  (0) 2008.06.26
Tomcat 5.X 버전에서 한글 파라메터 쓰기  (0) 2008.06.26
Posted by 양군이당
TAG JSON, XML, 변환

댓글을 달아 주세요

자바/Web2008. 6. 26. 02:20
출처 ace7min님의 블로그 | ace7min
원문 http://blog.naver.com/ace7min/28724114

클래스이름 = function(파라미터) {

    this.id = 파라미터;

    this.name = 파라미터;

}


Member = function( id, name ) {

    this.id = id;

    this.name = name;

}


var mem = new Member( 'testId', '창마이')


클래스이름.prototype.함수이름 = function( newId, newName ) {

    this.id = newId;

    this.name = newName;

}


Member.prototype.toString = function() {

    return this.id + "[" + this.name + "]";

}


이방법 이외에 Object() 를 이용한 방법으로


var mem = new Object();

mem.id = 'testId';

mem.name = '창마이';

mem.securityNo = '7700001000000';


mem.toString = function() {

    return this.name + "[" + this.id + "]";

}

 

alert( mem.toString() );


JSON 표기법


{ 이름1: 값1, 이름2: 값2, 이름3: 값3 }


var countries = {ko: '대한민국', fr: '프랑스', uk: '영국'};

var koName = countries.ko;

var frName = countries['fr'];


배열형식


[값0, 값1, 값2, 값3]


var countryCodes = ['ko', 'fr', 'uk', 'us'];

var idx0 = countryCodes[0]; //'ko'

var idx1 = countryCodes[2]; //'uk'


배열과 응용


var member = {

    name: '창마이',

    favorateColors: ['파랑', '노랑', '빨강']

};


var message = member.name + "님이 좋아하는 색상은 " +

     member.favorateColors.length + "개이고,";

message += "그중 첫 번째 색상은 " +

     member.favorateColors[0] + "입니다.";



JSON 표기법을 사용한 클래스 정의

 

클래스이름  = function( 파라미터 ) {

    ...

}


클래스이름.prototype = {

    함수명1: function( 파라미터 ) {

        ....

    },

    함수명1: function( 파라미터 ) {

        ....

    }

}


Ex)


Member = function(name, id, securityNo) {
 this.name = name;
 this.id = id;
 this.securityNo = securityNo;
}


Member.prototype = {
 setValue: function(newName, newId, newSecurityNo) {
  this.name = newName;
  this.id = newId;
  this.securityNo = newSecurityNo;
 },
 getAge: function() {
  var birthYear = parseInt(this.securityNo.substring(0, 2));
  var code = this.securityNo.substring(6,7);
  if (code == '1' || code == '2') {
   birthYear += 1900;
  } else if (code == '3' || code == '4') {
   birthYear += 2000;
  }
  var today = new Date();
  return today.getFullYear() - birthYear;
 },
 toString: function() {
  return this.name + "[" + this.id + "]";
 }
}




자바스크립트에서 패키지 정의하기


var ajax = new Object();

ajax.Request = function() {

    ...

}


ajax.Request.prototype = {

    someFunction = function() {

        ...

    },

    ...

}


위에 정의한 클래스 사용하기


var req = new ajax.Request();

req.someFunction();


중첩해서 패키지 만들기

 

var ajax = new Object();

ajax.xhr = new Object();

ajax.xhr.Request = function() {

    ...

}


// 아래와 같이 사용

var req = new ajax.xhr.Request();


빈 클래스 만들기


var ajax = {};

ajax.xhr = {};

ajax.xhr.Request = function() {

    ...

}


JSON 표기법에 대한 정보는 http://www.json.org/ 사이트에서 참고할 수 있다.

'자바 > Web' 카테고리의 다른 글

JSON  (0) 2008.06.26
JSON vs XML  (0) 2008.06.26
XML과 JSON 사이에 변환 패턴  (0) 2008.06.26
JavaScript 객체 JSON  (0) 2008.06.26
Java 객체를 이용해서 JSON객체를 위한 텍스트 생성하기  (0) 2008.06.26
Tomcat 5.X 버전에서 한글 파라메터 쓰기  (0) 2008.06.26
Posted by 양군이당
TAG java, JSON

댓글을 달아 주세요

자바/Web2008. 6. 26. 02:19

복사 http://blog.naver.com/eclips32/30020578345

Simple Java toolkit for JSON (JSON.simple)
==========================================

http://www.JSON.org/java/json_simple.zip

1.Why the Simple Java toolkit (also named as JSON.simple) for JSON?

  When I use JSON as the data exchange format between the AJAX client and JSP
  for the first time, what worry me mostly is how to encode Java strings and
  numbers correctly in the server side so the AJAX client will receive a well
  formed JSON data. When I looked into the 'JSON in Java' directory in JSON
  website,I found that wrappers to JSONObject and JSONArray can be simpler,
  due to the simplicity of JSON itself. So I wrote the JSON.simple package.

2.Is it simple,really?

  I think so. Take an example:

  import org.json.simple.JSONObject;

  JSONObject obj=new JSONObject();
  obj.put("name","foo");
  obj.put("num",new Integer(100));
  obj.put("balance",new Double(1000.21));
  obj.put("is_vip",new Boolean(true));
  obj.put("nickname",null);
  System.out.print(obj);

  Result:
  {"nickname":null,"num":100,"balance":1000.21,"is_vip":true,"name":"foo"}

  The JSONObject.toString() will escape controls and specials correctly.

3.How to use JSON.simple in JSP?

  Take an example in JSP:

  <%@page contentType="text/html; charset=UTF-8"%>
  <%@page import="org.json.simple.JSONObject"%>
  <%
    JSONObject obj=new JSONObject();
    obj.put("name","foo");
    obj.put("num",new Integer(100));
    obj.put("balance",new Double(1000.21));
    obj.put("is_vip",new Boolean(true));
    obj.put("nickname",null);
    out.print(obj);
    out.flush();
  %>

  So the AJAX client will get the responseText.

4.Some details about JSONObject?

  JSONObject inherits java.util.HashMap,so it don't have to worry about the
  mapping things between keys and values. Feel free to use the Map methods
  like get(), put(), and remove() and others. JSONObject.toString() will
  combine key value pairs to get the JSON data string. Values will be escaped
  into JSON quote string format if it's an instance of java.lang.String. Other
  type of instance like java.lang.Number,java.lang.Boolean,null,JSONObject and
  JSONArray will NOT escape, just take their java.lang.String.valueOf() result.
  null value will be the JSON 'null' in the result.

  It's still correct if you put an instance of JSONObject or JSONArray into an
  instance of JSONObject or JSONArray. Take the example about:

  JSONObject obj2=new JSONObject();
  obj2.put("phone","123456");
  obj2.put("zip","7890");
  obj.put("contact",obj2);
  System.out.print(obj);

  Result:
  {"nickname":null,"num":100,"contact":{"phone":"123456","zip":"7890"},"balance":1000.21,"is_vip":true,"name":"foo"}

  The method JSONObject.escape() is used to escape Java string into JSON quote
  string. Controls and specials will be escaped correctly into \b,\f,\r,\n,\t,
  \",\\,\/,\uhhhh.

5.Some detail about JSONArray?

  org.json.simple.JSONArray inherits java.util.ArrayList. Feel free to use the
  List methods like get(),add(),remove(),iterator() and so on. The rules of
  JSONArray.toString() is similar to JSONObject.toString(). Here's the example:

  import org.json.simple.JSONArray;

  JSONArray array=new JSONArray();
  array.add("hello");
  array.add(new Integer(123));
  array.add(new Boolean(false));
  array.add(null);
  array.add(new Double(123.45));
  array.add(obj2);//see above
  System.out.print(array);

  Result:
  ["hello",123,false,null,123.45,{"phone":"123456","zip":"7890"}]

6.What is JSONValue for?

  org.json.simple.JSONValue is use to parse JSON data into Java Object.
  In JSON, the topmost entity is JSON value, not the JSON object. But
  it's not necessary to wrap JSON string,boolean,number and null again,
  for the Java has already had the according classes: java.lang.String,
  java.lang.Boolean,java.lang.Number and null. The mapping is:

  JSON          Java
  ------------------------------------------------
  string      <=>   java.lang.String
  number      <=>   java.lang.Number
  true|false  <=>   java.lang.Boolean
  null        <=>   null
  array       <=>   org.json.simple.JSONArray
  object      <=>       org.json.simple.JSONObject
  ------------------------------------------------

  JSONValue has only one kind of method, JSONValue.parse(), which receives
  a java.io.Reader or java.lang.String. Return type of JSONValue.parse()
  is according to the mapping above. If the input is incorrect in syntax or
  there's exceptions during the parsing, I choose to return null, ignoring
  the exception: I have no idea if it's a serious implementaion, but I think
  it's convenient to the user.

  Here's the example:

  String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
  Object obj=JSONValue.parse(s);
  JSONArray array=(JSONArray)obj;
  System.out.println(array.get(1));
  JSONObject obj2=(JSONObject)array.get(1);
  System.out.println(obj2.get("1"));

  Result:
  {"1":{"2":{"3":{"4":[5,{"6":7}]}}}}
  {"2":{"3":{"4":[5,{"6":7}]}}}

7.About the author.

  I'm a Java EE developer on Linux.
  I'm working on web systems and information retrieval systems.
  I also develop 3D games and Flash games.

  You can contact me through:
  Fang Yidong<fangyidong@yahoo.com.cn>
  Fang Yidong<fangyidng@gmail.com>

  http://www.JSON.org/java/json_simple.zip

'자바 > Web' 카테고리의 다른 글

JSON  (0) 2008.06.26
JSON vs XML  (0) 2008.06.26
XML과 JSON 사이에 변환 패턴  (0) 2008.06.26
JavaScript 객체 JSON  (0) 2008.06.26
Java 객체를 이용해서 JSON객체를 위한 텍스트 생성하기  (0) 2008.06.26
Tomcat 5.X 버전에서 한글 파라메터 쓰기  (0) 2008.06.26
Posted by 양군이당
TAG java, JSON

댓글을 달아 주세요