01: /*
02: * Copyright 2005-2007 Noelios Consulting.
03: *
04: * The contents of this file are subject to the terms of the Common Development
05: * and Distribution License (the "License"). You may not use this file except in
06: * compliance with the License.
07: *
08: * You can obtain a copy of the license at
09: * http://www.opensource.org/licenses/cddl1.txt See the License for the specific
10: * language governing permissions and limitations under the License.
11: *
12: * When distributing Covered Code, include this CDDL HEADER in each file and
13: * include the License file at http://www.opensource.org/licenses/cddl1.txt If
14: * applicable, add the following below this CDDL HEADER, with the fields
15: * enclosed by brackets "[]" replaced with your own identifying information:
16: * Portions Copyright [yyyy] [name of copyright owner]
17: */
18:
19: package org.restlet.ext.json;
20:
21: import java.io.IOException;
22:
23: import org.json.JSONArray;
24: import org.json.JSONException;
25: import org.json.JSONObject;
26: import org.restlet.data.MediaType;
27: import org.restlet.resource.Representation;
28: import org.restlet.resource.StringRepresentation;
29:
30: /**
31: * Representation based on a JSON document. JSON stands for JavaScript Object
32: * Notation and is a lightweight data-interchange format.
33: *
34: * @author Jerome Louvel (contact@noelios.com)
35: * @see <a href="http://www.json.org">JSON home</a>
36: */
37: public class JsonRepresentation extends StringRepresentation {
38: /**
39: * Constructor.
40: *
41: * @param jsonRepresentation
42: * A source JSON representation to parse.
43: */
44: public JsonRepresentation(Representation jsonRepresentation)
45: throws IOException {
46: super (jsonRepresentation.getText(), MediaType.APPLICATION_JSON);
47: }
48:
49: /**
50: * Constructor from a JSON object.
51: *
52: * @param jsonObject
53: * The JSON object.
54: */
55: public JsonRepresentation(JSONObject jsonObject) {
56: super (jsonObject.toString(), MediaType.APPLICATION_JSON);
57: }
58:
59: /**
60: * Constructor from a JSON array.
61: *
62: * @param jsonArray
63: * The JSON array.
64: */
65: public JsonRepresentation(JSONArray jsonArray) {
66: super (jsonArray.toString(), MediaType.APPLICATION_JSON);
67: }
68:
69: /**
70: * Constructor from a JSON string.
71: *
72: * @param jsonString
73: * The JSON string.
74: */
75: public JsonRepresentation(String jsonString) {
76: super (jsonString, MediaType.APPLICATION_JSON);
77: }
78:
79: /**
80: * Converts the representation to a JSON object.
81: *
82: * @return The converted JSON object.
83: * @throws JSONException
84: */
85: public JSONObject toJsonObject() throws JSONException {
86: return new JSONObject(getText());
87: }
88:
89: /**
90: * Converts the representation to a JSON array.
91: *
92: * @return The converted JSON array.
93: * @throws JSONException
94: */
95: public JSONArray toJsonArray() throws JSONException {
96: return new JSONArray(getText());
97: }
98:
99: }
|