JSON (JavaScript Object Notation) is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects). The JSON format is specified in RFC 4627 by Douglas Crockford. The official Internet media type for JSON is application/json.

The JSON format is often used for transmitting structured data over a network connection in a process called serialization. Its main application is in AJAX web application programming, where it serves as an alternative to the traditional use of the XML format.

Supported data types

  1. Number (integer, real, or floating point)
  2. String (double-quoted Unicode with backslash escapement)
  3. Boolean (true and false)
  4. Array (an ordered sequence of values, comma-separated and enclosed in square brackets)
  5. Object (collection of key/value pairs, comma-separated and enclosed in curly brackets)
  6. null

Syntax

The following example shows the JSON representation of an object that describes a person. The object has string fields for first name and last name, contains an object representing the person’s address, and contains a list of phone numbers (an array).

01
02
03
04
05
06
07
08
09
10
11
12
13
14
{
    "firstName": "John",
    "lastName": "Smith",
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
    "phoneNumbers": [
        "212 732-1234",
        "646 123-4567"
    ]
}

Creating JSON data in Java

JSON.org has provided libraries to create/parse JSON data through Java code. These libraries can be used in any Java/J2EE project including Servlet, Struts, JSF, JSP etc and JSON data can be created.

Download JAR file json-rpc-1.0.jar (75 kb)

Use JSONObject class to create JSON data in Java. A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
import org.json.JSONObject;
 
...
...
 
JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");
 
...
 
String output = json.toString();
 
...

Thus by using toString() method you can get the output in JSON format.

JSON Array in Java

A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values. The internal form is an object having get and opt methods for accessing the values by index, and put methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object.

The constructor can convert a JSON text into a Java object. The toString method converts to JSON text.

JSONArray class can also be used to convert a collection of Java beans into JSON data. Similar to JSONObject, JSONArray has a put() method that can be used to put a collection into JSON object.

Thus by using JSONArray you can handle any type of data and convert corresponding JSON output.

Using json-lib library

JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.

Json-lib comes in two flavors, depending on the jdk compatibility. json-lib-x.x-jdk13 is compatible with JDK 1.3.1 and upwards. json-lib-x.x-jdk15 is compatible with JDK 1.5, includes support for Enums in JSONArray and JSONObject.

Download: json-lib.jar

Json-lib requires (at least) the following dependencies in your classpath:

  1. jakarta commons-lang 2.5
  2. jakarta commons-beanutils 1.8.0
  3. jakarta commons-collections 3.2.1
  4. jakarta commons-logging 1.1.1
  5. ezmorph 1.0.6

Example

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package net.viralpatel.java;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import net.sf.json.JSONObject;
 
public class JsonMain {
    public static void main(String[] args) {
 
        Map<String, Long> map = new HashMap<String, Long>();
        map.put("A", 10L);
        map.put("B", 20L);
        map.put("C", 30L);
 
        JSONObject json = new JSONObject();
        json.accumulateAll(map);
 
        System.out.println(json.toString());
 
        List<String> list = new ArrayList<String>();
        list.add("Sunday");
        list.add("Monday");
        list.add("Tuesday");
 
        json.accumulate("weekdays", list);
        System.out.println(json.toString());
    }
}

Output:

{"A":10,"B":20,"C":30}
{"A":10,"B":20,"C":30,"weekdays":["Sunday","Monday","Tuesday"]}


Using Google Gson library

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.

Gson Goals

  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  • Allow pre-existing unmodifiable objects to be converted to and from JSON
  • Extensive support of Java Generics
  • Allow custom representations for objects
  • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

Google Gson Example

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.List;
import com.google.gson.Gson;
 
public class Test {
 
    public static void main(String... args) throws Exception {
        String json =
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]"
                + "}]"
            + "}";
 
        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);
 
        // Show it.
        System.out.println(data);
    }
 
}
 
class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;
 
    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }
 
    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }
 
    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }

출처 - http://viralpatel.net/blogs/2009/02/creating-parsing-json-data-with-java-servlet-struts-jsp-json.html



'Development > JavaScript' 카테고리의 다른 글

JSON 예제 3 - file로 읽고 쓰기  (0) 2012.04.13
JSON 예제 2 - String에서 읽기  (0) 2012.04.13
JSON 소개  (0) 2012.03.27
window.onload - 페이지완전히 로딩후 처리하기위한 스크립트  (0) 2012.01.25
ECMAScript  (0) 2012.01.23
Posted by linuxism
,

JSP파일에 위쪽에 보면 아래와 같이 설정을 합니다.


<%@ page contentType="text/html; charset=XXXpageEncoding="XXX" %>

 

이때, 

pageEncoding : 

JSP소스코드의 캐릭터셋 - jsp페이지 자체의 캐릭터셋을 의미함


contentType내의 charset : 

HTTP 응답 캐릭터셋 - 웹브라우저(HTTP client)가 받아볼 페이지의 캐릭터셋을 의미

HTTP의 헤더에 그대로 이 내용이 들어가게 됩니다


 

예 제.

<%@ page contentType="text/html; charset=EUC-KRpageEncoding="UTF-8" %> 

jsp파일은 UTF-8로 인코딩도어 있고,  웹브라우저가 받을때는 EUC-KR로 받아봄


출처 - http://blog.naver.com/gmldbsdl6?Redirect=Log&logNo=80155290841

'Development > JSP & Servlet' 카테고리의 다른 글

getParameter와 getAttribute 차이  (0) 2012.03.28
JSP에서 JSTL과 EL(Expression Language) 사용하기  (0) 2012.03.28
jsp - *.jsp를 WEB-INF 아래에 숨겨라  (0) 2012.03.23
request.setCharacterEncoding  (0) 2012.03.23
JSP  (0) 2012.02.05
Posted by linuxism
,



maven을 사용하면서 dependency를 추가할때마다

missing artifact라는 에러 메세지가.

그때마다 구글링하면서 문제를 간간히 해결하고있던 참에 대체 왜이러는걸까. 이유가 궁금했다.

maven에서는 groupid-artifactId-version.classifier.type 으로 파일 명을 관리하는데

해당 파일이 없는 경우였던 것.

        <dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<type>bundle</type>
</dependency>
 
문제가 있었던 두 라이브러리.

json의 경우 classifier를 추가하였고,

log4j의 경우 bundle로 지정되어 있던 type을 삭제하였다.

사 내 메이븐 리포지토리를 직접 살펴봄으로 더욱 정확하게? 이유를 인지하였다. :)


출처 - http://icecreamie.tistory.com/144

'IDE & Build > Maven' 카테고리의 다른 글

maven - war 파일 배포  (0) 2012.05.07
Nexus 소개 및 구성  (0) 2012.04.14
Maven 설치 3_repository 설정  (0) 2012.03.25
Maven 설치 2  (0) 2012.03.25
Maven 설치 1  (0) 2012.03.25
Posted by linuxism
,