20 | */
21 | public class JSONValue {
22 |
23 | /**
24 | * Parse JSON text into java object from the input source. Please use
25 | * parseWithException() if you don't want to ignore the exception.
26 | *
27 | * @see JSONParser#parse(Reader)
28 | * @see #parseWithException(Reader)
29 | *
30 | * @return Instance of the following: JSONObject, JSONArray, String,
31 | * java.lang.Number, java.lang.Boolean, null
32 | *
33 | */
34 | public static Object parse(Reader in) {
35 | try {
36 | return new JSONParserStream().parse(in);
37 | } catch (Exception e) {
38 | return null;
39 | }
40 | }
41 |
42 | public static Object parse(String s) {
43 | try {
44 | return new JSONParser().parse(s);
45 | } catch (Exception e) {
46 | return null;
47 | }
48 | }
49 |
50 | /**
51 | * Parse JSON text into java object from the input source.
52 | *
53 | * @see parser.JSONParser
54 | *
55 | * @return Instance of the following: JSONObject, JSONArray, String,
56 | * java.lang.Number, java.lang.Boolean, null
57 | */
58 | public static Object parseWithException(Reader in) throws IOException, ParseException {
59 | return new JSONParserStream().parse(in, ContainerFactory.FACTORY);
60 | }
61 |
62 | public static Object parseWithException(String s) throws ParseException {
63 | return new JSONParser().parse(s, ContainerFactory.FACTORY);
64 | }
65 |
66 | /**
67 | * Encode an object into JSON text and write it to out.
68 | *
69 | * If this object is a Map or a List, and it's also a JSONStreamAware or a
70 | * JSONAware, JSONStreamAware or JSONAware will be considered firstly.
71 | *
72 | *
73 | * @see JSONObject#writeJSONString(Map, Appendable)
74 | * @see JSONArray#writeJSONString(List, Appendable)
75 | */
76 | @SuppressWarnings("unchecked")
77 | public static void writeJSONString(Object value, Appendable out) throws IOException {
78 | if (value == null) {
79 | out.append("null");
80 | return;
81 | }
82 |
83 | if (value instanceof String) {
84 | out.append('"');
85 | escape((String) value, out);
86 | out.append('"');
87 | return;
88 | }
89 |
90 | if (value instanceof Number) {
91 | if (value instanceof Double) {
92 | if (((Double) value).isInfinite())
93 | out.append("null");
94 | else
95 | out.append(value.toString());
96 | } else if (value instanceof Float) {
97 | if (((Float) value).isInfinite())
98 | out.append("null");
99 | else
100 | out.append(value.toString());
101 | } else {
102 | out.append(value.toString());
103 | }
104 | return;
105 | }
106 |
107 | if (value instanceof Boolean)
108 | out.append(value.toString());
109 | else if ((value instanceof JSONStreamAware))
110 | ((JSONStreamAware) value).writeJSONString(out);
111 | else if ((value instanceof JSONAware))
112 | out.append(((JSONAware) value).toJSONString());
113 | else if (value instanceof Map, ?>)
114 | JSONObject.writeJSONString((Map) value, out);
115 | else if (value instanceof List>)
116 | JSONArray.writeJSONString((List) value, out);
117 | else {
118 | out.append('"');
119 | out.append(escape(value.toString()));
120 | out.append('"');
121 | }
122 | }
123 |
124 | /**
125 | * Convert an object to JSON text.
126 | *
127 | * If this object is a Map or a List, and it's also a JSONAware, JSONAware
128 | * will be considered firstly.
129 | *
130 | *
131 | * @see net.minidev.json.JSONObject#toJSONString(Map)
132 | * @see net.minidev.json.JSONArray#toJSONString(List)
133 | *
134 | * @return JSON text, or "null" if value is null or it's an NaN or an INF
135 | * number.
136 | */
137 | public static String toJSONString(Object value) {
138 | StringBuilder sb = new StringBuilder();
139 | try {
140 | writeJSONString(value, sb);
141 | } catch (IOException e) {
142 | // can not append on a StringBuilder
143 | }
144 | return sb.toString();
145 | }
146 |
147 | /**
148 | * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters
149 | * (U+0000 through U+001F).
150 | */
151 | public static String escape(String s) {
152 | if (s == null)
153 | return null;
154 | StringBuilder sb = new StringBuilder();
155 | JStylerObj.escape(s, sb);
156 | return sb.toString();
157 | }
158 |
159 | public static void escape(String s, Appendable ap) {
160 | if (s == null)
161 | return;
162 | JStylerObj.escape(s, ap);
163 | }
164 | }
165 |
--------------------------------------------------------------------------------
/json-smart-mini/src/main/java/net/minidev/json/JStylerObj.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json;
2 |
3 | import java.io.IOException;
4 |
5 | /**
6 | * protected class used to stored Internal methods
7 | *
8 | * @author Uriel Chemouni
9 | */
10 | class JStylerObj {
11 |
12 | public static boolean isSpace(char c) {
13 | return (c == '\r' || c == '\n' || c == '\t' || c == ' ');
14 | }
15 |
16 | public static boolean isSpecialChar(char c) {
17 | return (c == '\b' || c == '\f' || c == '\n');
18 | }
19 |
20 | public static boolean isSpecialOpen(char c) {
21 | return (c == '{' || c == '[' || c == ',' || c == ':');
22 | }
23 |
24 | public static boolean isSpecialClose(char c) {
25 | return (c == '}' || c == ']' || c == ',' || c == ':');
26 | }
27 |
28 | public static boolean isSpecial(char c) {
29 | return (c == '{' || c == '[' || c == ',' || c == '}' || c == ']' || c == ':' || c == '\'' || c == '"');
30 | }
31 |
32 | public static boolean isUnicode(char c) {
33 | return ((c >= '\u0000' && c <= '\u001F') || (c >= '\u007F' && c <= '\u009F') || (c >= '\u2000' && c <= '\u20FF'));
34 | }
35 |
36 | public static boolean isKeyword(String s) {
37 | if (s.length() < 3)
38 | return false;
39 | char c = s.charAt(0);
40 | if (c == 'n')
41 | return s.equals("null");
42 | if (c == 't')
43 | return s.equals("true");
44 | if (c == 'f')
45 | return s.equals("false");
46 | if (c == 'N')
47 | return s.equals("NaN");
48 | return false;
49 | }
50 |
51 | /**
52 | * Escape special chars form String including /
53 | *
54 | * @param s
55 | * - Must not be null.
56 | * @param sb
57 | */
58 | public static void escape(String s, Appendable sb) {
59 | try {
60 | int len = s.length();
61 | for (int i = 0; i < len; i++) {
62 | char ch = s.charAt(i);
63 | switch (ch) {
64 | case '"':
65 | sb.append("\\\"");
66 | break;
67 | case '\\':
68 | sb.append("\\\\");
69 | break;
70 | case '\b':
71 | sb.append("\\b");
72 | break;
73 | case '\f':
74 | sb.append("\\f");
75 | break;
76 | case '\n':
77 | sb.append("\\n");
78 | break;
79 | case '\r':
80 | sb.append("\\r");
81 | break;
82 | case '\t':
83 | sb.append("\\t");
84 | break;
85 | case '/':
86 | sb.append("\\/");
87 | break;
88 | default:
89 | // Reference:
90 | // http://www.unicode.org/versions/Unicode5.1.0/
91 | if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F')
92 | || (ch >= '\u2000' && ch <= '\u20FF')) {
93 | sb.append("\\u");
94 | String hex = "0123456789ABCDEF";
95 | sb.append(hex.charAt(ch >> 12 & 0x0F));
96 | sb.append(hex.charAt(ch >> 8 & 0x0F));
97 | sb.append(hex.charAt(ch >> 4 & 0x0F));
98 | sb.append(hex.charAt(ch >> 0 & 0x0F));
99 | } else {
100 | sb.append(ch);
101 | }
102 | }
103 | }
104 | } catch (IOException e) {
105 | throw new RuntimeException("Impossible Error");
106 | }
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/json-smart-mini/src/main/java/net/minidev/json/parser/ContainerFactory.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | import net.minidev.json.JSONArray;
7 | import net.minidev.json.JSONObject;
8 | import net.minidev.json.parser.ContainerFactory;
9 |
10 | /**
11 | * Container factory for creating containers for JSON object and JSON array.
12 | *
13 | * @author FangYidong
14 | */
15 | public class ContainerFactory {
16 | public final static ContainerFactory FACTORY = new ContainerFactory();
17 |
18 | /**
19 | * @return A Map instance to store JSON object, or null if you want to use JSONObject.
20 | */
21 | public Map createObjectContainer() {
22 | return new JSONObject();
23 | }
24 |
25 | /**
26 | * @return A List instance to store JSON array, or null if you want to use JSONArray.
27 | */
28 | public List creatArrayContainer() {
29 | return new JSONArray();
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/json-smart-mini/src/main/java/net/minidev/json/parser/ContentHandler.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | import java.io.IOException;
4 | import java.io.Reader;
5 |
6 | /**
7 | * A simplified and stoppable SAX-like content handler for stream processing of
8 | * JSON text.
9 | *
10 | * @see org.xml.sax.ContentHandler
11 | * @see JSONParser#parse(Reader, ContainerFactory)
12 | *
13 | * @author FangYidong
14 | */
15 | public interface ContentHandler {
16 | /**
17 | * Receive notification of the beginning of JSON processing. The parser will
18 | * invoke this method only once.
19 | *
20 | * @throws ParseException
21 | * - JSONParser will stop and throw the same exception to the
22 | * caller when receiving this exception.
23 | */
24 | void startJSON() throws ParseException, IOException;
25 |
26 | /**
27 | * Receive notification of the end of JSON processing.
28 | *
29 | * @throws ParseException
30 | */
31 | void endJSON() throws ParseException, IOException;
32 |
33 | /**
34 | * Receive notification of the beginning of a JSON object.
35 | *
36 | * @return false if the handler wants to stop parsing after return.
37 | * @throws ParseException
38 | * - JSONParser will stop and throw the same exception to the
39 | * caller when receiving this exception.
40 | * @see #endJSON
41 | */
42 | boolean startObject() throws ParseException, IOException;
43 |
44 | /**
45 | * Receive notification of the end of a JSON object.
46 | *
47 | * @return false if the handler wants to stop parsing after return.
48 | * @throws ParseException
49 | *
50 | * @see #startObject
51 | */
52 | boolean endObject() throws ParseException, IOException;
53 |
54 | /**
55 | * Receive notification of the beginning of a JSON object entry.
56 | *
57 | * @param key
58 | * - Key of a JSON object entry.
59 | *
60 | * @return false if the handler wants to stop parsing after return.
61 | * @throws ParseException
62 | *
63 | * @see #endObjectEntry
64 | */
65 | boolean startObjectEntry(String key) throws ParseException, IOException;
66 |
67 | /**
68 | * Receive notification of the end of the value of previous object entry.
69 | *
70 | * @return false if the handler wants to stop parsing after return.
71 | * @throws ParseException
72 | *
73 | * @see #startObjectEntry
74 | */
75 | boolean endObjectEntry() throws ParseException, IOException;
76 |
77 | /**
78 | * Receive notification of the beginning of a JSON array.
79 | *
80 | * @return false if the handler wants to stop parsing after return.
81 | * @throws ParseException
82 | *
83 | * @see #endArray
84 | */
85 | boolean startArray() throws ParseException, IOException;
86 |
87 | /**
88 | * Receive notification of the end of a JSON array.
89 | *
90 | * @return false if the handler wants to stop parsing after return.
91 | * @throws ParseException
92 | *
93 | * @see #startArray
94 | */
95 | boolean endArray() throws ParseException, IOException;
96 |
97 | /**
98 | * Receive notification of the JSON primitive values: java.lang.String,
99 | * java.lang.Number, java.lang.Boolean null
100 | *
101 | * @param value
102 | * - Instance of the following: java.lang.String,
103 | * java.lang.Number, java.lang.Boolean null
104 | *
105 | * @return false if the handler wants to stop parsing after return.
106 | * @throws ParseException
107 | */
108 | boolean primitive(Object value) throws ParseException, IOException;
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/json-smart-mini/src/main/java/net/minidev/json/parser/JSONParser.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | import java.io.IOException;
4 | import java.io.Reader;
5 |
6 | /**
7 | * Parser for JSON text. Please note that JSONParser is NOT thread-safe.
8 | *
9 | * @author Uriel Chemouni
10 | */
11 | public class JSONParser extends JSONParserStream {
12 |
13 | protected static boolean[] stopArray = new boolean[126];
14 | protected static boolean[] stopKey = new boolean[126];
15 | protected static boolean[] stopValue = new boolean[126];
16 | protected static boolean[] stopX = new boolean[126];
17 | static {
18 | stopKey[':'] = true;
19 | stopValue[','] = stopValue['}'] = true;
20 | stopArray[','] = stopArray[']'] = true;
21 | }
22 |
23 | public Object parse(String in) throws IOException, ParseException {
24 | return parse(new FStringReader(in), ContainerFactory.FACTORY);
25 | }
26 |
27 | public Object parse(String in, ContainerFactory containerFactory) throws ParseException {
28 | try {
29 | return parse(new FStringReader(in), containerFactory);
30 | } catch (IOException e) {
31 | // cant not be throws
32 | return null;
33 | }
34 | }
35 |
36 | /**
37 | * Non Syncronized limited StringReader
38 | */
39 | private static class FStringReader extends Reader {
40 | private String str;
41 | private int length;
42 | private int next = 0;
43 |
44 | public FStringReader(String s) {
45 | this.str = s;
46 | this.length = s.length();
47 | }
48 |
49 | public int read() throws IOException {
50 | if (next >= length)
51 | return -1;
52 | return str.charAt(next++);
53 | }
54 |
55 | public int read(char cbuf[], int off, int len) throws IOException {
56 | if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) {
57 | throw new IndexOutOfBoundsException();
58 | } else if (len == 0) {
59 | return 0;
60 | }
61 | if (next >= length)
62 | return -1;
63 | int n = Math.min(length - next, len);
64 | str.getChars(next, next + n, cbuf, off);
65 | next += n;
66 | return n;
67 | }
68 |
69 | public boolean ready() throws IOException {
70 | return true;
71 | }
72 |
73 | public boolean markSupported() {
74 | return false;
75 | }
76 |
77 | public void close() {
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/json-smart-mini/src/main/java/net/minidev/json/parser/JSONParserStream.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | import java.io.IOException;
4 | import java.io.Reader;
5 | import java.math.BigDecimal;
6 | import java.math.BigInteger;
7 | import java.util.List;
8 | import java.util.Map;
9 |
10 |
11 |
12 | import static net.minidev.json.parser.ParseException.*;
13 | import static net.minidev.json.parser.JSONParser.*;
14 |
15 | /**
16 | * Parser for JSON text. Please note that JSONParser is NOT thread-safe.
17 | *
18 | * @author Uriel Chemouni
19 | */
20 | public class JSONParserStream {
21 | public final static int EOI = -1;
22 | private int c;
23 | private ContainerFactory containerFactory;
24 | private Reader in;
25 | private int pos;
26 | private StringBuilder sb = new StringBuilder();
27 | private String xs;
28 |
29 | //
30 | //
31 | //
32 | //
33 | //
34 | //
35 | //
36 | //
37 | /**
38 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
39 | * generated by a ContainerFactory
40 | */
41 | public Object parse(Reader in) throws ParseException, IOException {
42 | return parse(in, ContainerFactory.FACTORY);
43 | }
44 |
45 | /**
46 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
47 | * generated by a ContainerFactory
48 | */
49 | public Object parse(Reader in, ContainerFactory containerFactory) throws ParseException, IOException {
50 |
51 | this.in = in;
52 | this.containerFactory = containerFactory;
53 | this.c = in.read();
54 | this.pos = 0;
55 | //
56 | //
57 | //
58 | Object result = readMain(stopX);
59 | xs = null;
60 | return result;
61 | }
62 |
63 | final private void read() throws IOException {
64 | c = in.read();
65 |
66 | pos++;
67 | }
68 |
69 | private List readArray() throws ParseException, IOException {
70 | List obj = containerFactory.creatArrayContainer();
71 | if (c != '[')
72 | throw new RuntimeException("Internal Error");
73 | read();
74 |
75 | for (;;) {
76 | switch (c) {
77 | case ' ':
78 | case '\r':
79 | case '\n':
80 | case '\t':
81 | read();
82 | continue;
83 | case ']':
84 | read(); /* unstack */
85 |
86 | return obj;
87 | case ':':
88 | case '}':
89 | throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c);
90 | case ',':
91 | read();
92 | continue;
93 | case EOI:
94 | throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF");
95 | default:
96 | obj.add(readMain(stopArray));
97 | continue;
98 | }
99 | }
100 | }
101 |
102 | /**
103 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
104 | * generated by a ContainerFactory
105 | */
106 | private Object readMain(boolean stop[]) throws ParseException, IOException {
107 | for (;;) {
108 | switch (c) {
109 | // skip spaces
110 | case ' ':
111 | case '\r':
112 | case '\n':
113 | case '\t':
114 | read();
115 | continue;
116 | // invalid stats
117 | case ':':
118 | case '}':
119 | case ']':
120 | throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c);
121 | // start object
122 | case '{':
123 | return readObject();
124 | // start Array
125 | case '[':
126 | return readArray();
127 | // start string
128 | case '"':
129 | case '\'':
130 | //
131 | //
132 | return readString();
133 | // string or null
134 | case 'n':
135 | xs = readNQString(stop);
136 | if ("null".equals(xs)) {
137 |
138 | return null;
139 | }
140 | //
141 | //
142 | //
143 | return xs;
144 | // string or false
145 | case 'f':
146 | xs = readNQString(stop);
147 | if ("false".equals(xs)) {
148 |
149 | return Boolean.FALSE;
150 | }
151 | //
152 | //
153 | //
154 | return xs;
155 | // string or true
156 | case 't':
157 | xs = readNQString(stop);
158 | if ("true".equals(xs)) {
159 |
160 | return Boolean.TRUE;
161 | }
162 | //
163 | //
164 | //
165 | return xs;
166 | // string or NaN
167 | case 'N':
168 | xs = readNQString(stop);
169 | //
170 | //
171 | if ("NaN".equals(xs)) {
172 |
173 | return Float.valueOf(Float.NaN);
174 | }
175 | //
176 | //
177 | //
178 | return xs;
179 | // digits
180 | case '0':
181 | case '1':
182 | case '2':
183 | case '3':
184 | case '4':
185 | case '5':
186 | case '6':
187 | case '7':
188 | case '8':
189 | case '9':
190 | case '-':
191 | //
192 | //
193 | return readNumber(stop);
194 | default:
195 | //
196 | //
197 | //
198 | //
199 | return readNQString(stop);
200 | }
201 | }
202 | }
203 |
204 | private String readNQString(boolean[] stop) throws IOException {
205 | sb.delete(0, sb.length());
206 | skipNQString(stop);
207 | return sb.toString().trim();
208 | }
209 |
210 | private Object readNumber(boolean[] stop) throws ParseException, IOException {
211 | sb.delete(0, sb.length());
212 | sb.append((char) c);// skip first char digit or -
213 | read();
214 | skipDigits();
215 | if (c != '.' && c != 'E' && c != 'e') {
216 | skipSpace();
217 | if (!stop[c]) {
218 | // convert string
219 | skipNQString(stop);
220 | //
221 | //
222 | //
223 | return sb.toString().trim();
224 | }
225 | xs = sb.toString().trim();
226 | if (xs.length() > 20)
227 | return new BigInteger(xs);
228 | try {
229 | long v = Long.parseLong(xs);
230 | if (v >= (long) Integer.MIN_VALUE && v <= (long) Integer.MAX_VALUE)
231 | return Integer.valueOf((int) v);
232 | return Long.valueOf(v);
233 | } catch (NumberFormatException e) {
234 | return new BigInteger(xs);
235 | }
236 | }
237 | if (c == '.') {
238 | sb.append((char) c);
239 | read();
240 | skipDigits();
241 | }
242 | if (c != 'E' && c != 'e') {
243 | skipSpace();
244 | if (!stop[c]) {
245 | // convert string
246 | skipNQString(stop);
247 | //
248 | //
249 | //
250 | return sb.toString().trim();
251 | }
252 | String num = sb.toString().trim();
253 | try {
254 | if (num.length() > 18) // follow JSjonIJ parssing methode
255 | return new BigDecimal(num);
256 | return Double.parseDouble(num);
257 | } catch (NumberFormatException e) {
258 | throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs);
259 | }
260 | }
261 | sb.append('E');
262 | read();
263 | if (c == '+' || c == '-' || c >= '0' && c <= '9') {
264 | sb.append((char) c);
265 | read(); // skip first char
266 | skipDigits();
267 | skipSpace();
268 | if (!stop[c]) {
269 | // convert string
270 | skipNQString(stop);
271 | return sb.toString().trim();
272 | }
273 | try {
274 | return Double.parseDouble(sb.toString().trim());
275 | } catch (NumberFormatException e) {
276 | throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs);
277 | }
278 | } else {
279 | skipNQString(stop);
280 | return sb.toString().trim();
281 | //
282 | //
283 | //
284 | //
285 | //
286 | //
287 | }
288 | // throw new ParseException(pos - 1, ERROR_UNEXPECTED_CHAR, null);
289 | }
290 |
291 | private Map readObject() throws ParseException, IOException {
292 | Map obj = this.containerFactory.createObjectContainer();
293 | if (c != '{')
294 | throw new RuntimeException("Internal Error");
295 |
296 | for (;;) {
297 | read();
298 | switch (c) {
299 | case ' ':
300 | case '\r':
301 | case '\t':
302 | case '\n':
303 | continue;
304 | case ':':
305 | case ']':
306 | case '[':
307 | case '{':
308 | throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c);
309 | case '}':
310 | read(); /* unstack */
311 |
312 | return obj;
313 | case ',':
314 | continue;
315 | case '"':
316 | case '\'':
317 | default:
318 | String key;
319 | if (c == '\"' || c == '\'')
320 | key = readString();
321 | else {
322 | key = readNQString(stopKey);
323 | }
324 | //
325 | //
326 | //
327 | while (c != ':' && c != EOI) {
328 | read();
329 | }
330 | if (c == EOI)
331 | throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, null);
332 | read(); /* skip : */
333 | obj.put(key, readMain(stopValue));
334 |
335 | if (c == '}') {
336 | read(); /* unstack */
337 |
338 | return obj;
339 | } /* if c==, confinue */
340 | continue;
341 | }
342 | }
343 | }
344 |
345 | private String readString() throws ParseException, IOException {
346 | //
347 | //
348 | sb.delete(0, sb.length());
349 | /* assert (c == '\"' || c == '\'') */
350 | //
351 | //
352 | //
353 | //
354 | //
355 | //
356 | //
357 | //
358 | //
359 | //
360 | char sep = (char) c;
361 | for (;;) {
362 | read();
363 | switch (c) {
364 | case EOI:
365 | throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, null);
366 | case '"':
367 | case '\'':
368 | if (sep == c) {
369 | read();
370 | return sb.toString();
371 | }
372 | sb.append((char) c);
373 | break;
374 | case '\\':
375 | read();
376 | switch (c) {
377 | case 't':
378 | sb.append('\t');
379 | break;
380 | case 'n':
381 | sb.append('\n');
382 | break;
383 | case 'r':
384 | sb.append('\r');
385 | break;
386 | case 'f':
387 | sb.append('\f');
388 | break;
389 | case 'b':
390 | sb.append('\b');
391 | break;
392 | case '\\':
393 | sb.append('\\');
394 | break;
395 | case '/':
396 | sb.append('/');
397 | break;
398 | case '\'':
399 | sb.append('\'');
400 | break;
401 | case '"':
402 | sb.append('"');
403 | break;
404 | case 'u':
405 | sb.append(readUnicode());
406 | break;
407 | default:
408 | break;
409 | }
410 | break;
411 | case '\b':
412 | case '\t':
413 | case '\f':
414 | case '\r':
415 | case '\n':
416 | continue;
417 | default:
418 | sb.append((char) c);
419 | }
420 | }
421 | }
422 |
423 | private char readUnicode() throws ParseException, IOException {
424 | int value = 0;
425 | for (int i = 0; i < 4; i++) {
426 | value = value * 16;
427 | read();
428 | if (c >= '0' && c <= '9')
429 | value += c - '0';
430 | else if (c >= 'A' && c <= 'F')
431 | value += (c - 'A') + 10;
432 | else if (c >= 'a' && c <= 'f')
433 | value += (c - 'a') + 10;
434 | else if (c == EOI)
435 | throw new ParseException(pos, ERROR_UNEXPECTED_EOF, "EOF");
436 | else
437 | throw new ParseException(pos, ERROR_UNEXPECTED_UNICODE, c);
438 | }
439 | return (char) value;
440 | }
441 |
442 | private void skipDigits() throws IOException {
443 | for (;;) {
444 | if (c == EOI)
445 | return;
446 | if (c < '0' || c > '9')
447 | return;
448 | sb.append((char) c);
449 | read();
450 | }
451 | }
452 |
453 | private void skipNQString(boolean[] stop) throws IOException {
454 | for (;;) {
455 | if (c == EOI)
456 | return;
457 | if (c >= 0 && c <= 125 && stop[c])
458 | return;
459 | sb.append((char) c);
460 | read();
461 | }
462 | }
463 |
464 | private void skipSpace() throws IOException {
465 | for (;;) {
466 | if (c == EOI)
467 | return;
468 | if (c != ' ' && c != '\r' && c != '\t' && c != '\n')
469 | return;
470 | sb.append((char) c);
471 | read();
472 | }
473 | }
474 | }
475 |
--------------------------------------------------------------------------------
/json-smart-mini/src/main/java/net/minidev/json/parser/ParseException.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /**
4 | * ParseException explains why and where the error occurs in source JSON text.
5 | *
6 | * @author Uriel Chemouni
7 | */
8 | public class ParseException extends Exception {
9 | private static final long serialVersionUID = 8879024178584091857L;
10 |
11 | public static final int ERROR_UNEXPECTED_CHAR = 0;
12 | public static final int ERROR_UNEXPECTED_TOKEN = 1;
13 | // public static final int ERROR_UNEXPECTED_EXCEPTION = 2;
14 | public static final int ERROR_UNEXPECTED_EOF = 3;
15 | public static final int ERROR_UNEXPECTED_UNICODE = 4;
16 |
17 | private int errorType;
18 | private Object unexpectedObject;
19 | private int position;
20 |
21 | public ParseException(int position, int errorType, Object unexpectedObject) {
22 | super(toMessage(position, errorType, unexpectedObject));
23 | this.position = position;
24 | this.errorType = errorType;
25 | this.unexpectedObject = unexpectedObject;
26 | }
27 |
28 | public int getErrorType() {
29 | return errorType;
30 | }
31 |
32 | /**
33 | * @return The character position (starting with 0) of the input where the
34 | * error occurs.
35 | */
36 | public int getPosition() {
37 | return position;
38 | }
39 |
40 | /**
41 | * @return One of the following base on the value of errorType:
42 | * ERROR_UNEXPECTED_CHAR java.lang.Character ERROR_UNEXPECTED_TOKEN
43 | * ERROR_UNEXPECTED_EXCEPTION java.lang.Exception
44 | */
45 | public Object getUnexpectedObject() {
46 | return unexpectedObject;
47 | }
48 |
49 | public String toString() {
50 | return getMessage();
51 | }
52 |
53 | private static String toMessage(int position, int errorType, Object unexpectedObject) {
54 | StringBuilder sb = new StringBuilder();
55 |
56 | if (errorType == ERROR_UNEXPECTED_CHAR) {
57 | sb.append("Unexpected character (");
58 | sb.append(unexpectedObject);
59 | sb.append(") at position ");
60 | sb.append(position);
61 | sb.append(".");
62 | } else if (errorType == ERROR_UNEXPECTED_TOKEN) {
63 | sb.append("Unexpected token ");
64 | sb.append(unexpectedObject);
65 | sb.append(" at position ");
66 | sb.append(position);
67 | sb.append(".");
68 | } else if (errorType == ERROR_UNEXPECTED_EOF) {
69 | sb.append("Unexpected End Of File position ");
70 | sb.append(position);
71 | sb.append(": ");
72 | sb.append(unexpectedObject);
73 | } else if (errorType == ERROR_UNEXPECTED_UNICODE) {
74 | sb.append("Unexpected unicode escape sequence ");
75 | sb.append(unexpectedObject);
76 | sb.append(" at position ");
77 | sb.append(position);
78 | sb.append(".");
79 | } else {
80 | sb.append("Unkown error at position ");
81 | sb.append(position);
82 | sb.append(".");
83 | }
84 | // sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject);
85 | // break;
86 | return sb.toString();
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/json-smart-mini/src/test/java/net/minidev/json/test/TestFloat.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import net.minidev.json.JSONObject;
4 | import net.minidev.json.parser.JSONParser;
5 | import junit.framework.TestCase;
6 |
7 | public class TestFloat extends TestCase {
8 |
9 | public void testFloat() throws Exception {
10 | String[] asNumber = new String[] { "1.0", "123.456", "1.0E1", "123.456E12", "1.0E+1", "123.456E+12", "1.0E-1",
11 | "123.456E-12", "1.0e1", "123.456e12", "1.0e+1", "123.456e+12", "1.0e-1", "123.456e-12" };
12 | JSONParser p = new JSONParser();
13 | for (String s : asNumber) {
14 | String json = "{v:" + s + "}";
15 | Double val = Double.valueOf(s.trim());
16 | JSONObject obj = (JSONObject) p.parse(json);
17 | Object value = obj.get("v");
18 | assertEquals("Should be parse as double", val, value);
19 | }
20 | }
21 |
22 | public void testNonFloat() throws Exception {
23 | String[] asStr = new String[] { "1.0%", "123.45.6", "1.0E", "++123.456E12", "+-01", "1.0E+1.2" };
24 | JSONParser p = new JSONParser();
25 | for (String s : asStr) {
26 | String json = "{v:" + s + "}";
27 | JSONObject obj = (JSONObject) p.parse(json);
28 | assertEquals("Should be parse as string", s, obj.get("v"));
29 |
30 | String correct = "{\"v\":\"" + s + "\"}";
31 | assertEquals("Should be re serialized as", correct, obj.toJSONString());
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/json-smart-mini/src/test/java/net/minidev/json/test/TestInts.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import java.math.BigInteger;
4 |
5 | import net.minidev.json.JSONObject;
6 | import net.minidev.json.parser.JSONParser;
7 | import junit.framework.TestCase;
8 |
9 | public class TestInts extends TestCase {
10 |
11 | public void testIntMax() throws Exception {
12 | String s = "{t:" + Integer.MAX_VALUE + "}";
13 | JSONObject o = (JSONObject) new JSONParser().parse(s);
14 | assertEquals(o.get("t"), Integer.MAX_VALUE);
15 | }
16 |
17 | public void testIntMin() throws Exception {
18 | String s = "{t:" + Integer.MIN_VALUE + "}";
19 | JSONObject o = (JSONObject) new JSONParser().parse(s);
20 | assertEquals(o.get("t"), Integer.MIN_VALUE);
21 | }
22 |
23 | public void testInt() throws Exception {
24 | String s = "{t:90}";
25 | JSONObject o = (JSONObject) new JSONParser().parse(s);
26 | assertEquals(o.get("t"), 90);
27 | }
28 |
29 | public void testIntNeg() throws Exception {
30 | String s = "{t:-90}";
31 | JSONObject o = (JSONObject) new JSONParser().parse(s);
32 | assertEquals(o.get("t"), -90);
33 | }
34 |
35 | public void testBigInt() throws Exception {
36 | String bigText = Integer.MAX_VALUE + "" + Integer.MAX_VALUE + "" + Integer.MAX_VALUE + "" + Integer.MAX_VALUE;
37 | BigInteger big = new BigInteger(bigText, 10);
38 | String s = "{t:" + bigText + "}";
39 | JSONObject o = (JSONObject) new JSONParser().parse(s);
40 | assertEquals(o.get("t"), big);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/json-smart-mini/src/test/java/net/minidev/json/test/TestKeyword.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import net.minidev.json.JSONObject;
4 | import net.minidev.json.parser.JSONParser;
5 | import junit.framework.TestCase;
6 |
7 | public class TestKeyword extends TestCase {
8 |
9 | public void testBool() throws Exception {
10 | String s = "{t:true}";
11 | JSONObject o = (JSONObject) new JSONParser().parse(s);
12 | assertEquals(o.get("t"), true);
13 |
14 | s = "{t:false}";
15 | o = (JSONObject) new JSONParser().parse(s);
16 | assertEquals(o.get("t"), false);
17 | }
18 |
19 | public void testNull() throws Exception {
20 | String s = "{t:null}";
21 | JSONObject o = (JSONObject) new JSONParser().parse(s);
22 | assertNull(o.get("t"));
23 | }
24 |
25 | public void testNaN() throws Exception {
26 | String s = "{t:NaN}";
27 | JSONObject o = (JSONObject) new JSONParser().parse(s);
28 | assertEquals(o.get("t"), Float.NaN);
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/json-smart-mini/src/test/java/net/minidev/json/test/TestString.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import net.minidev.json.JSONObject;
4 | import net.minidev.json.parser.JSONParser;
5 | import junit.framework.TestCase;
6 |
7 | public class TestString extends TestCase {
8 |
9 | public void testS1() throws Exception {
10 | String text = "My Test";
11 | String s = "{t:\"" + text + "\"}";
12 | JSONObject o = (JSONObject) new JSONParser().parse(s);
13 | assertEquals(o.get("t"), text);
14 | }
15 |
16 | public void testS2() throws Exception {
17 | String text = "My Test";
18 | String s = "{t:'" + text + "'}";
19 | JSONObject o = (JSONObject) new JSONParser().parse(s);
20 | assertEquals(o.get("t"), text);
21 | }
22 |
23 | public void testSEscape() throws Exception {
24 | String text = "My\r\nTest";
25 | String text2 = "My\\r\\nTest";
26 | String s = "{t:'" + text2 + "'}";
27 | JSONObject o = (JSONObject) new JSONParser().parse(s);
28 | assertEquals(o.get("t"), text);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/json-smart-sample/pom.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 | 4.0.0
5 |
6 | json-smart-sample
7 | jar
8 |
9 |
10 | net.minidev
11 | parent
12 | 1.1
13 | ../parent/pom.xml
14 |
15 |
16 | JSON Small and Fast Parser
17 |
18 |
19 | Json-smart Sample code.
20 |
21 |
22 |
23 |
24 | net.minidev
25 | json-smart
26 |
27 |
28 |
--------------------------------------------------------------------------------
/json-smart/ChangeLog.txt:
--------------------------------------------------------------------------------
1 | Version 1.3.2 (2021/05/03)
2 | * fix CVE-2021-27568
3 | Version 1.0.4 (2011/05/02)
4 | * First Public version
5 | Version 1.0.4-1 (2011/05/03)
6 | * Performance Improvement
7 | Version 1.0.4-2 (2011/05/06)
8 | * add support for non protected string starting with digits.
9 | * add Junit tests
10 |
11 |
--------------------------------------------------------------------------------
/json-smart/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/json-smart/pom.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 | 4.0.0
5 |
6 | json-smart
7 | bundle
8 | 1.3.3
9 |
10 |
11 | net.minidev
12 | parent
13 | 1.3.2
14 | ../parent/pom.xml
15 |
16 |
17 | JSON Small and Fast Parser
18 |
19 |
20 | JSON (JavaScript Object Notation) is a lightweight data-interchange format.
21 | It is easy for humans to read and write. It is easy for machines to parse and generate.
22 | It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition
23 | - December 1999. JSON is a text format that is completely language independent but uses
24 | conventions that are familiar to programmers of the C-family of languages, including C, C++, C#,
25 | Java, JavaScript, Perl, Python, and many others.
26 | These properties make JSON an ideal data-interchange language.
27 |
28 |
29 |
30 |
31 |
32 | org.apache.felix
33 | maven-bundle-plugin
34 | 2.3.7
35 | true
36 |
37 |
38 | ${project.groupId}.${project.artifactId}
39 | ${project.artifactId}
40 | ${project.version}
41 | net.minidev.json,net.minidev.json.parser,net.minidev.json.serialiser
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 | junit
52 | junit
53 | test
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/json-smart/readme.txt:
--------------------------------------------------------------------------------
1 | @see:
2 | http://code.google.com/p/json-smart/
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/JSONArray.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.IOException;
19 | import java.util.ArrayList;
20 | import java.util.List;
21 |
22 | import net.minidev.json.reader.JsonWriter;
23 |
24 | /**
25 | * A JSON array. JSONObject supports java.util.List interface.
26 | *
27 | * @author FangYidong
28 | * @author Uriel Chemouni
29 | */
30 | public class JSONArray extends ArrayList implements List, JSONAwareEx, JSONStreamAwareEx {
31 | private static final long serialVersionUID = 9106884089231309568L;
32 |
33 | public static String toJSONString(List extends Object> list) {
34 | return toJSONString(list, JSONValue.COMPRESSION);
35 | }
36 |
37 | /**
38 | * Convert a list to JSON text. The result is a JSON array. If this list is
39 | * also a JSONAware, JSONAware specific behaviours will be omitted at this
40 | * top level.
41 | *
42 | * @see net.minidev.json.JSONValue#toJSONString(Object)
43 | *
44 | * @param list
45 | * @param compression
46 | * Indicate compression level
47 | * @return JSON text, or "null" if list is null.
48 | */
49 | public static String toJSONString(List extends Object> list, JSONStyle compression) {
50 | StringBuilder sb = new StringBuilder();
51 | try {
52 | writeJSONString(list, sb, compression);
53 | } catch (IOException e) {
54 | // Can not append on a string builder
55 | }
56 | return sb.toString();
57 | }
58 |
59 | /**
60 | * Encode a list into JSON text and write it to out. If this list is also a
61 | * JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific
62 | * behaviours will be ignored at this top level.
63 | *
64 | * @see JSONValue#writeJSONString(Object, Appendable)
65 | *
66 | * @param list
67 | * @param out
68 | */
69 | public static void writeJSONString(Iterable extends Object> list, Appendable out, JSONStyle compression)
70 | throws IOException {
71 | if (list == null) {
72 | out.append("null");
73 | return;
74 | }
75 | JsonWriter.JSONIterableWriter.writeJSONString(list, out, compression);
76 | }
77 |
78 | public static void writeJSONString(List extends Object> list, Appendable out) throws IOException {
79 | writeJSONString(list, out, JSONValue.COMPRESSION);
80 | }
81 |
82 | public void merge(Object o2) {
83 | JSONObject.merge(this, o2);
84 | }
85 |
86 | /**
87 | * Explicitely Serialize Object as JSon String
88 | */
89 | public String toJSONString() {
90 | return toJSONString(this, JSONValue.COMPRESSION);
91 | }
92 |
93 | public String toJSONString(JSONStyle compression) {
94 | return toJSONString(this, compression);
95 | }
96 |
97 | /**
98 | * Override natif toStirng()
99 | */
100 | public String toString() {
101 | return toJSONString();
102 | }
103 |
104 | /**
105 | * JSONAwareEx inferface
106 | *
107 | * @param compression
108 | * compression param
109 | */
110 | public String toString(JSONStyle compression) {
111 | return toJSONString(compression);
112 | }
113 |
114 | public void writeJSONString(Appendable out) throws IOException {
115 | writeJSONString(this, out, JSONValue.COMPRESSION);
116 | }
117 |
118 | public void writeJSONString(Appendable out, JSONStyle compression) throws IOException {
119 | writeJSONString(this, out, compression);
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/JSONAware.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | /**
19 | * Beans that support customized output of JSON text shall implement this
20 | * interface.
21 | *
22 | * @author FangYidong
23 | */
24 | public interface JSONAware {
25 | /**
26 | * @return JSON text
27 | */
28 | String toJSONString();
29 | }
30 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/JSONAwareEx.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | /**
19 | * Beans that support advanced output of JSON text shall implement this
20 | * interface.
21 | *
22 | * Adding compressions and formating features
23 | *
24 | * @author Uriel Chemouni
25 | */
26 |
27 | public interface JSONAwareEx extends JSONAware {
28 | /**
29 | * @return JSON text
30 | */
31 | String toJSONString(JSONStyle compression);
32 | }
33 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/JSONObject.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.IOException;
19 | import java.util.HashMap;
20 | import java.util.Map;
21 |
22 | import net.minidev.json.reader.JsonWriter;
23 |
24 | /**
25 | * A JSON object. Key value pairs are unordered. JSONObject supports
26 | * java.util.Map interface.
27 | *
28 | * @author FangYidong
29 | * @author Uriel Chemouni
30 | */
31 | public class JSONObject extends HashMap implements JSONAware, JSONAwareEx, JSONStreamAwareEx {
32 | private static final long serialVersionUID = -503443796854799292L;
33 |
34 | public JSONObject() {
35 | super();
36 | }
37 |
38 | // /**
39 | // * Allow simply casting to Map
40 | // */
41 | // @SuppressWarnings("unchecked")
42 | // public T cast() {
43 | // return (T) this;
44 | // }
45 |
46 | /**
47 | * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters
48 | * (U+0000 through U+001F). It's the same as JSONValue.escape() only for
49 | * compatibility here.
50 | *
51 | * @see JSONValue#escape(String)
52 | */
53 | public static String escape(String s) {
54 | return JSONValue.escape(s);
55 | }
56 |
57 | public static String toJSONString(Map map) {
58 | return toJSONString(map, JSONValue.COMPRESSION);
59 | }
60 |
61 | /**
62 | * Convert a map to JSON text. The result is a JSON object. If this map is
63 | * also a JSONAware, JSONAware specific behaviours will be omitted at this
64 | * top level.
65 | *
66 | * @see net.minidev.json.JSONValue#toJSONString(Object)
67 | *
68 | * @param map
69 | * @return JSON text, or "null" if map is null.
70 | */
71 | public static String toJSONString(Map map, JSONStyle compression) {
72 | StringBuilder sb = new StringBuilder();
73 | try {
74 | writeJSON(map, sb, compression);
75 | } catch (IOException e) {
76 | // can not append on a StringBuilder
77 | }
78 | return sb.toString();
79 | }
80 |
81 | // /**
82 | // * return a Key:value entry as stream
83 | // */
84 | // public static String toString(String key, Object value) {
85 | // return toString(key, value, JSONValue.COMPRESSION);
86 | // }
87 |
88 | // /**
89 | // * return a Key:value entry as stream
90 | // */
91 | // public static String toString(String key, Object value, JSONStyle
92 | // compression) {
93 | // StringBuilder sb = new StringBuilder();
94 | // try {
95 | // writeJSONKV(key, value, sb, compression);
96 | // } catch (IOException e) {
97 | // // can not append on a StringBuilder
98 | // }
99 | // return sb.toString();
100 | // }
101 |
102 | /**
103 | * Allows creation of a JSONObject from a Map. After that, both the
104 | * generated JSONObject and the Map can be modified independently.
105 | */
106 | public JSONObject(Map map) {
107 | super(map);
108 | }
109 |
110 | public static void writeJSON(Map map, Appendable out) throws IOException {
111 | writeJSON(map, out, JSONValue.COMPRESSION);
112 | }
113 |
114 | /**
115 | * Encode a map into JSON text and write it to out. If this map is also a
116 | * JSONAware or JSONStreamAware, JSONAware or JSONStreamAware specific
117 | * behaviours will be ignored at this top level.
118 | *
119 | * @see JSONValue#writeJSONString(Object, Appendable)
120 | */
121 | public static void writeJSON(Map map, Appendable out, JSONStyle compression)
122 | throws IOException {
123 | if (map == null) {
124 | out.append("null");
125 | return;
126 | }
127 | JsonWriter.JSONMapWriter.writeJSONString(map, out, compression);
128 | }
129 |
130 | /**
131 | * serialize Object as json to an stream
132 | */
133 | public void writeJSONString(Appendable out) throws IOException {
134 | writeJSON(this, out, JSONValue.COMPRESSION);
135 | }
136 |
137 | /**
138 | * serialize Object as json to an stream
139 | */
140 | public void writeJSONString(Appendable out, JSONStyle compression) throws IOException {
141 | writeJSON(this, out, compression);
142 | }
143 |
144 | public void merge(Object o2) {
145 | merge(this, o2);
146 | }
147 |
148 | protected static JSONObject merge(JSONObject o1, Object o2) {
149 | if (o2 == null)
150 | return o1;
151 | if (o2 instanceof JSONObject)
152 | return merge(o1, (JSONObject) o2);
153 | throw new RuntimeException("JSON megre can not merge JSONObject with " + o2.getClass());
154 | }
155 |
156 | private static JSONObject merge(JSONObject o1, JSONObject o2) {
157 | if (o2 == null)
158 | return o1;
159 | for (String key : o1.keySet()) {
160 | Object value1 = o1.get(key);
161 | Object value2 = o2.get(key);
162 | if (value2 == null)
163 | continue;
164 | if (value1 instanceof JSONArray) {
165 | o1.put(key, merge((JSONArray) value1, value2));
166 | continue;
167 | }
168 | if (value1 instanceof JSONObject) {
169 | o1.put(key, merge((JSONObject) value1, value2));
170 | continue;
171 | }
172 | if (value1.equals(value2))
173 | continue;
174 | if (value1.getClass().equals(value2.getClass()))
175 | throw new RuntimeException("JSON merge can not merge two " + value1.getClass().getName()
176 | + " Object together");
177 | throw new RuntimeException("JSON merge can not merge " + value1.getClass().getName() + " with "
178 | + value2.getClass().getName());
179 | }
180 | for (String key : o2.keySet()) {
181 | if (o1.containsKey(key))
182 | continue;
183 | o1.put(key, o2.get(key));
184 | }
185 | return o1;
186 | }
187 |
188 | protected static JSONArray merge(JSONArray o1, Object o2) {
189 | if (o2 == null)
190 | return o1;
191 | if (o1 instanceof JSONArray)
192 | return merge(o1, (JSONArray) o2);
193 | o1.add(o2);
194 | return o1;
195 | }
196 |
197 | private static JSONArray merge(JSONArray o1, JSONArray o2) {
198 | o1.addAll(o2);
199 | return o1;
200 | }
201 |
202 | public String toJSONString() {
203 | return toJSONString(this, JSONValue.COMPRESSION);
204 | }
205 |
206 | public String toJSONString(JSONStyle compression) {
207 | return toJSONString(this, compression);
208 | }
209 |
210 | public String toString(JSONStyle compression) {
211 | return toJSONString(this, compression);
212 | }
213 |
214 | public String toString() {
215 | return toJSONString(this, JSONValue.COMPRESSION);
216 | }
217 | }
218 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/JSONStreamAware.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.IOException;
19 |
20 | /**
21 | * Beans that support customized output of JSON text to a writer shall implement
22 | * this interface.
23 | *
24 | * @author FangYidong
25 | */
26 | public interface JSONStreamAware {
27 | /**
28 | * write JSON string to out.
29 | */
30 | void writeJSONString(Appendable out) throws IOException;
31 | }
32 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/JSONStreamAwareEx.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.IOException;
19 |
20 | /**
21 | * Beans that support customized output of JSON text to a writer shall implement
22 | * this interface.
23 | *
24 | * @author FangYidong
25 | */
26 | public interface JSONStreamAwareEx extends JSONStreamAware {
27 | /**
28 | * write JSON string to out.
29 | */
30 | void writeJSONString(Appendable out, JSONStyle compression) throws IOException;
31 | }
32 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/JSONStyle.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.IOException;
19 |
20 | import net.minidev.json.JStylerObj.MustProtect;
21 | import net.minidev.json.JStylerObj.StringProtector;
22 |
23 | /**
24 | * JSONStyle object configure JSonSerializer reducing output size
25 | *
26 | * @author Uriel Chemouni
27 | */
28 | public class JSONStyle {
29 | /**
30 | * for advanced usage sample see
31 | *
32 | * @see net.minidev.json.test.TestCompressorFlags
33 | */
34 | public final static int FLAG_PROTECT_KEYS = 1;
35 | public final static int FLAG_PROTECT_4WEB = 2;
36 | public final static int FLAG_PROTECT_VALUES = 4;
37 | /**
38 | * AGRESSIVE have no effect without PROTECT_KEYS or PROTECT_VALUE
39 | *
40 | * AGRESSIVE mode allows Json-smart to not protect String containing special
41 | * chars
42 | */
43 | public final static int FLAG_AGRESSIVE = 8;
44 | /**
45 | * @since 1.3.1
46 | */
47 | public final static int FLAG_IGNORE_NULL = 16;
48 |
49 | public final static JSONStyle NO_COMPRESS = new JSONStyle();
50 | public final static JSONStyle MAX_COMPRESS = new JSONStyle(-1);
51 | /**
52 | * @since 1.0.9.1
53 | */
54 | public final static JSONStyle LT_COMPRESS = new JSONStyle(FLAG_PROTECT_4WEB);
55 |
56 | private boolean _protectKeys;
57 | private boolean _protect4Web;
58 | private boolean _protectValues;
59 | private boolean _ignore_null;
60 |
61 | private MustProtect mpKey;
62 | private MustProtect mpValue;
63 |
64 | private StringProtector esc;
65 |
66 | public JSONStyle(int FLAG) {
67 | _protectKeys = (FLAG & FLAG_PROTECT_KEYS) == 0;
68 | _protectValues = (FLAG & FLAG_PROTECT_VALUES) == 0;
69 | _protect4Web = (FLAG & FLAG_PROTECT_4WEB) == 0;
70 | _ignore_null = (FLAG & FLAG_IGNORE_NULL) > 0;
71 | MustProtect mp;
72 | if ((FLAG & FLAG_AGRESSIVE) > 0)
73 | mp = JStylerObj.MP_AGGRESIVE;
74 | else
75 | mp = JStylerObj.MP_SIMPLE;
76 |
77 | if (_protectValues)
78 | mpValue = JStylerObj.MP_TRUE;
79 | else
80 | mpValue = mp;
81 |
82 | if (_protectKeys)
83 | mpKey = JStylerObj.MP_TRUE;
84 | else
85 | mpKey = mp;
86 |
87 | if (_protect4Web)
88 | esc = JStylerObj.ESCAPE4Web;
89 | else
90 | esc = JStylerObj.ESCAPE_LT;
91 | }
92 |
93 | public JSONStyle() {
94 | this(0);
95 | }
96 |
97 | public boolean protectKeys() {
98 | return _protectKeys;
99 | }
100 |
101 | public boolean protectValues() {
102 | return _protectValues;
103 | }
104 |
105 | public boolean protect4Web() {
106 | return _protect4Web;
107 | }
108 |
109 | public boolean ignoreNull() {
110 | return _ignore_null;
111 | }
112 |
113 | public boolean indent() {
114 | return false;
115 | }
116 |
117 | public boolean mustProtectKey(String s) {
118 | return mpKey.mustBeProtect(s);
119 | }
120 |
121 | public boolean mustProtectValue(String s) {
122 | return mpValue.mustBeProtect(s);
123 | }
124 |
125 | public void writeString(Appendable out, String value) throws IOException {
126 | if (!this.mustProtectValue(value))
127 | out.append(value);
128 | else {
129 | out.append('"');
130 | JSONValue.escape(value, out, this);
131 | out.append('"');
132 | }
133 | }
134 |
135 | public void escape(String s, Appendable out) {
136 | esc.escape(s, out);
137 | }
138 |
139 | /**
140 | * begin Object
141 | */
142 | public void objectStart(Appendable out) throws IOException {
143 | out.append('{');
144 | }
145 |
146 | /**
147 | * terminate Object
148 | */
149 | public void objectStop(Appendable out) throws IOException {
150 | out.append('}');
151 | }
152 |
153 | /**
154 | * Start the first Obeject element
155 | */
156 | public void objectFirstStart(Appendable out) throws IOException {
157 | }
158 |
159 | /**
160 | * Start a new Object element
161 | */
162 | public void objectNext(Appendable out) throws IOException {
163 | out.append(',');
164 | }
165 |
166 | /**
167 | * End Of Object element
168 | */
169 | public void objectElmStop(Appendable out) throws IOException {
170 | }
171 |
172 | /**
173 | * end of Key in json Object
174 | */
175 | public void objectEndOfKey(Appendable out) throws IOException {
176 | out.append(':');
177 | }
178 |
179 | /**
180 | * Array start
181 | */
182 | public void arrayStart(Appendable out) throws IOException {
183 | out.append('[');
184 | }
185 |
186 | /**
187 | * Array Done
188 | */
189 | public void arrayStop(Appendable out) throws IOException {
190 | out.append(']');
191 | }
192 |
193 | /**
194 | * Start the first Array element
195 | */
196 | public void arrayfirstObject(Appendable out) throws IOException {
197 | }
198 |
199 | /**
200 | * Start a new Array element
201 | */
202 | public void arrayNextElm(Appendable out) throws IOException {
203 | out.append(',');
204 | }
205 |
206 | /**
207 | * End of an Array element
208 | */
209 | public void arrayObjectEnd(Appendable out) throws IOException {
210 | }
211 |
212 | }
213 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/JSONStyleIdent.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.IOException;
19 |
20 | /**
21 | * This class is used to format JSon output, fot a better humain readability
22 | *
23 | * @author Uriel Chemouni
24 | */
25 | public class JSONStyleIdent extends JSONStyle {
26 | char identChar = ' ';
27 | String newline = "\n";
28 | int deep = 0;
29 |
30 | public JSONStyleIdent(int FLAG) {
31 | super(FLAG);
32 | }
33 |
34 | public JSONStyleIdent() {
35 | super();
36 | }
37 |
38 | private void ident(Appendable out) throws IOException {
39 | out.append(newline);
40 | for (int i = 0; i < deep; i++)
41 | out.append(this.identChar);
42 | }
43 |
44 | /**
45 | * begin Object
46 | */
47 | public void objectStart(Appendable out) throws IOException {
48 | out.append('{');
49 | deep++;
50 | ident(out);
51 | }
52 |
53 | /**
54 | * terminate Object
55 | */
56 | public void objectStop(Appendable out) throws IOException {
57 | deep--;
58 | ident(out);
59 | out.append('}');
60 | }
61 |
62 | /**
63 | * Start the first Obeject element
64 | */
65 | public void objectFirstStart(Appendable out) throws IOException {
66 | }
67 |
68 | /**
69 | * Start a new Object element
70 | */
71 | public void objectNext(Appendable out) throws IOException {
72 | out.append(',');
73 | ident(out);
74 | }
75 |
76 | /**
77 | * End Of Object element
78 | */
79 | public void objectElmStop(Appendable out) throws IOException {
80 | }
81 |
82 | /**
83 | * end of Key in json Object
84 | */
85 | public void objectEndOfKey(Appendable out) throws IOException {
86 | out.append(':');
87 | }
88 |
89 | /**
90 | * Array start
91 | */
92 | public void arrayStart(Appendable out) throws IOException {
93 | out.append('[');
94 | deep++;
95 | ident(out);
96 | }
97 |
98 | /**
99 | * Array Done
100 | */
101 | public void arrayStop(Appendable out) throws IOException {
102 | deep--;
103 | ident(out);
104 | out.append(']');
105 | }
106 |
107 | /**
108 | * Start the first Array element
109 | */
110 | public void arrayfirstObject(Appendable out) throws IOException {
111 | }
112 |
113 | /**
114 | * Start a new Array element
115 | */
116 | public void arrayNextElm(Appendable out) throws IOException {
117 | out.append(',');
118 | ident(out);
119 | }
120 |
121 | /**
122 | * End of an Array element
123 | */
124 | public void arrayObjectEnd(Appendable out) throws IOException {
125 | }
126 |
127 | }
128 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/JSONUtil.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 | /**
20 | * @author Uriel Chemouni
21 | */
22 | public class JSONUtil {
23 | public static String getSetterName(String key) {
24 | int len = key.length();
25 | char[] b = new char[len + 3];
26 | b[0] = 's';
27 | b[1] = 'e';
28 | b[2] = 't';
29 | char c = key.charAt(0);
30 | if (c >= 'a' && c <= 'z')
31 | c += 'A' - 'a';
32 | b[3] = c;
33 | for (int i = 1; i < len; i++) {
34 | b[i + 3] = key.charAt(i);
35 | }
36 | return new String(b);
37 | }
38 |
39 | public static String getGetterName(String key) {
40 | int len = key.length();
41 | char[] b = new char[len + 3];
42 | b[0] = 'g';
43 | b[1] = 'e';
44 | b[2] = 't';
45 | char c = key.charAt(0);
46 | if (c >= 'a' && c <= 'z')
47 | c += 'A' - 'a';
48 | b[3] = c;
49 | for (int i = 1; i < len; i++) {
50 | b[i + 3] = key.charAt(i);
51 | }
52 | return new String(b);
53 | }
54 |
55 | public static String getIsName(String key) {
56 | int len = key.length();
57 | char[] b = new char[len + 2];
58 | b[0] = 'i';
59 | b[1] = 's';
60 | char c = key.charAt(0);
61 | if (c >= 'a' && c <= 'z')
62 | c += 'A' - 'a';
63 | b[2] = c;
64 | for (int i = 1; i < len; i++) {
65 | b[i + 2] = key.charAt(i);
66 | }
67 | return new String(b);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/JStylerObj.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.IOException;
19 |
20 | /**
21 | * protected class used to stored Internal methods
22 | *
23 | * @author Uriel Chemouni
24 | */
25 | class JStylerObj {
26 |
27 | public final static MPSimple MP_SIMPLE = new MPSimple();
28 | public final static MPTrue MP_TRUE = new MPTrue();
29 | public final static MPAgressive MP_AGGRESIVE = new MPAgressive();
30 |
31 | public final static EscapeLT ESCAPE_LT = new EscapeLT();
32 | public final static Escape4Web ESCAPE4Web = new Escape4Web();
33 |
34 | public static interface MustProtect {
35 | public boolean mustBeProtect(String s);
36 | }
37 |
38 | private static class MPTrue implements MustProtect {
39 | public boolean mustBeProtect(String s) {
40 | return true;
41 | }
42 | }
43 |
44 | private static class MPSimple implements MustProtect {
45 | /**
46 | * can a String can be store without enclosing quotes. ie: should not
47 | * contain any special json char
48 | *
49 | * @param s
50 | * @return
51 | */
52 | public boolean mustBeProtect(String s) {
53 | if (s == null)
54 | return false;
55 | int len = s.length();
56 | if (len == 0)
57 | return true;
58 | if (s.trim() != s)
59 | return true;
60 |
61 | char ch = s.charAt(0);
62 | if (ch >= '0' && ch <= '9' || ch == '-')
63 | return true;
64 |
65 | for (int i = 0; i < len; i++) {
66 | ch = s.charAt(i);
67 | if (isSpace(ch))
68 | return true;
69 | if (isSpecial(ch))
70 | return true;
71 | if (isSpecialChar(ch))
72 | return true;
73 | if (isUnicode(ch))
74 | return true;
75 | }
76 | // keyword check
77 | if (isKeyword(s))
78 | return true;
79 | return false;
80 | }
81 | }
82 |
83 | private static class MPAgressive implements MustProtect {
84 | public boolean mustBeProtect(final String s) {
85 | if (s == null)
86 | return false;
87 | int len = s.length();
88 | // protect empty String
89 | if (len == 0)
90 | return true;
91 |
92 | // protect trimable String
93 | if (s.trim() != s)
94 | return true;
95 |
96 | // json special char
97 | char ch = s.charAt(0);
98 | if (isSpecial(ch) || isUnicode(ch))
99 | return true;
100 |
101 | for (int i = 1; i < len; i++) {
102 | ch = s.charAt(i);
103 | if (isSpecialClose(ch) || isUnicode(ch))
104 | return true;
105 | }
106 | // keyWord must be protect
107 | if (isKeyword(s))
108 | return true;
109 | // Digit like text must be protect
110 | ch = s.charAt(0);
111 | // only test String if First Ch is a digit
112 | if (ch >= '0' && ch <= '9' || ch == '-') {
113 | int p = 1;
114 | // skip first digits
115 | for (; p < len; p++) {
116 | ch = s.charAt(p);
117 | if (ch < '0' || ch > '9')
118 | break;
119 | }
120 | // int/long
121 | if (p == len)
122 | return true;
123 | // Floating point
124 | if (ch == '.') {
125 | p++;
126 | }
127 | // Skip digits
128 | for (; p < len; p++) {
129 | ch = s.charAt(p);
130 | if (ch < '0' || ch > '9')
131 | break;
132 | }
133 | if (p == len)
134 | return true; // can be read as an floating number
135 | // Double
136 | if (ch == 'E' || ch == 'e') {
137 | p++;
138 | if (p == len) // no power data not a digits
139 | return false;
140 | ch = s.charAt(p);
141 | if (ch == '+' || ch == '-') {
142 | p++;
143 | ch = s.charAt(p);
144 | }
145 | }
146 | if (p == len) // no power data => not a digit
147 | return false;
148 |
149 | for (; p < len; p++) {
150 | ch = s.charAt(p);
151 | if (ch < '0' || ch > '9')
152 | break;
153 | }
154 | // floating point With power of data.
155 | if (p == len)
156 | return true;
157 | return false;
158 | }
159 | return false;
160 | }
161 | }
162 |
163 | public static boolean isSpace(char c) {
164 | return (c == '\r' || c == '\n' || c == '\t' || c == ' ');
165 | }
166 |
167 | public static boolean isSpecialChar(char c) {
168 | return (c == '\b' || c == '\f' || c == '\n');
169 | }
170 |
171 | public static boolean isSpecialOpen(char c) {
172 | return (c == '{' || c == '[' || c == ',' || c == ':');
173 | }
174 |
175 | public static boolean isSpecialClose(char c) {
176 | return (c == '}' || c == ']' || c == ',' || c == ':');
177 | }
178 |
179 | public static boolean isSpecial(char c) {
180 | return (c == '{' || c == '[' || c == ',' || c == '}' || c == ']' || c == ':' || c == '\'' || c == '"');
181 | }
182 |
183 | public static boolean isUnicode(char c) {
184 | return ((c >= '\u0000' && c <= '\u001F') || (c >= '\u007F' && c <= '\u009F') || (c >= '\u2000' && c <= '\u20FF'));
185 | }
186 |
187 | public static boolean isKeyword(String s) {
188 | if (s.length() < 3)
189 | return false;
190 | char c = s.charAt(0);
191 | if (c == 'n')
192 | return s.equals("null");
193 | if (c == 't')
194 | return s.equals("true");
195 | if (c == 'f')
196 | return s.equals("false");
197 | if (c == 'N')
198 | return s.equals("NaN");
199 | return false;
200 | }
201 |
202 | public static interface StringProtector {
203 | public void escape(String s, Appendable out);
204 | }
205 |
206 | private static class EscapeLT implements StringProtector {
207 | /**
208 | * Escape special chars form String except /
209 | *
210 | * @param s
211 | * - Must not be null.
212 | * @param out
213 | */
214 | public void escape(String s, Appendable out) {
215 | try {
216 | int len = s.length();
217 | for (int i = 0; i < len; i++) {
218 | char ch = s.charAt(i);
219 | switch (ch) {
220 | case '"':
221 | out.append("\\\"");
222 | break;
223 | case '\\':
224 | out.append("\\\\");
225 | break;
226 | case '\b':
227 | out.append("\\b");
228 | break;
229 | case '\f':
230 | out.append("\\f");
231 | break;
232 | case '\n':
233 | out.append("\\n");
234 | break;
235 | case '\r':
236 | out.append("\\r");
237 | break;
238 | case '\t':
239 | out.append("\\t");
240 | break;
241 | default:
242 | // Reference:
243 | // http://www.unicode.org/versions/Unicode5.1.0/
244 | if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F')
245 | || (ch >= '\u2000' && ch <= '\u20FF')) {
246 | out.append("\\u");
247 | String hex = "0123456789ABCDEF";
248 | out.append(hex.charAt(ch >> 12 & 0x000F));
249 | out.append(hex.charAt(ch >> 8 & 0x000F));
250 | out.append(hex.charAt(ch >> 4 & 0x000F));
251 | out.append(hex.charAt(ch >> 0 & 0x000F));
252 | } else {
253 | out.append(ch);
254 | }
255 | }
256 | }
257 | } catch (IOException e) {
258 | throw new RuntimeException("Impossible Exeption");
259 | }
260 | }
261 | }
262 |
263 | private static class Escape4Web implements StringProtector {
264 |
265 | /**
266 | * Escape special chars form String including /
267 | *
268 | * @param s
269 | * - Must not be null.
270 | * @param sb
271 | */
272 | public void escape(String s, Appendable sb) {
273 | try {
274 | int len = s.length();
275 | for (int i = 0; i < len; i++) {
276 | char ch = s.charAt(i);
277 | switch (ch) {
278 | case '"':
279 | sb.append("\\\"");
280 | break;
281 | case '\\':
282 | sb.append("\\\\");
283 | break;
284 | case '\b':
285 | sb.append("\\b");
286 | break;
287 | case '\f':
288 | sb.append("\\f");
289 | break;
290 | case '\n':
291 | sb.append("\\n");
292 | break;
293 | case '\r':
294 | sb.append("\\r");
295 | break;
296 | case '\t':
297 | sb.append("\\t");
298 | break;
299 | case '/':
300 | sb.append("\\/");
301 | break;
302 | default:
303 | // Reference:
304 | // http://www.unicode.org/versions/Unicode5.1.0/
305 | if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F')
306 | || (ch >= '\u2000' && ch <= '\u20FF')) {
307 | sb.append("\\u");
308 | String hex = "0123456789ABCDEF";
309 | sb.append(hex.charAt(ch >> 12 & 0x0F));
310 | sb.append(hex.charAt(ch >> 8 & 0x0F));
311 | sb.append(hex.charAt(ch >> 4 & 0x0F));
312 | sb.append(hex.charAt(ch >> 0 & 0x0F));
313 | } else {
314 | sb.append(ch);
315 | }
316 | }
317 | }
318 | } catch (IOException e) {
319 | throw new RuntimeException("Impossible Error");
320 | }
321 | }
322 | }
323 | }
324 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/ContainerFactory.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.util.LinkedHashMap;
19 | import java.util.List;
20 | import java.util.Map;
21 |
22 | import net.minidev.json.JSONArray;
23 | import net.minidev.json.JSONObject;
24 |
25 | /**
26 | * Container factory for creating containers for JSON object and JSON array.
27 | *
28 | * @author Uriel Chemouni
29 | */
30 | public interface ContainerFactory {
31 | /**
32 | * @return A Map instance to build JSON object.
33 | */
34 | public Map createObjectContainer();
35 |
36 | /**
37 | * @return A List instance to store JSON array.
38 | */
39 | public List createArrayContainer();
40 |
41 | /**
42 | * Default factory
43 | */
44 | public final static ContainerFactory FACTORY_SIMPLE = new ContainerFactory() {
45 |
46 | // @Override JDK 1.5 compatibility change
47 | public Map createObjectContainer() {
48 | return new JSONObject();
49 | }
50 |
51 | // @Override JDK 1.5 compatibility change
52 | public List createArrayContainer() {
53 | return new JSONArray();
54 | }
55 | };
56 |
57 | public final static ContainerFactory FACTORY_ORDERED = new ContainerFactory() {
58 |
59 | // @Override JDK 1.5 compatibility change
60 | public Map createObjectContainer() {
61 | return new LinkedHashMap();
62 | }
63 |
64 | // @Override JDK 1.5 compatibility change
65 | public List createArrayContainer() {
66 | return new JSONArray();
67 | }
68 | };
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/ContentHandler.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.IOException;
19 |
20 | /**
21 | * A simplified and stoppable SAX-like content handler for stream processing of
22 | * JSON text.
23 | *
24 | * @see org.xml.sax.ContentHandler
25 | *
26 | * @author FangYidong
27 | */
28 | public interface ContentHandler {
29 | /**
30 | * Receive notification of the beginning of JSON processing. The parser will
31 | * invoke this method only once.
32 | *
33 | * @throws ParseException
34 | * - JSONParser will stop and throw the same exception to the
35 | * caller when receiving this exception.
36 | */
37 | void startJSON() throws ParseException, IOException;
38 |
39 | /**
40 | * Receive notification of the end of JSON processing.
41 | *
42 | * @throws ParseException
43 | */
44 | void endJSON() throws ParseException, IOException;
45 |
46 | /**
47 | * Receive notification of the beginning of a JSON object.
48 | *
49 | * @return false if the handler wants to stop parsing after return.
50 | * @throws ParseException
51 | * - JSONParser will stop and throw the same exception to the
52 | * caller when receiving this exception.
53 | * @see #endJSON
54 | */
55 | boolean startObject() throws ParseException, IOException;
56 |
57 | /**
58 | * Receive notification of the end of a JSON object.
59 | *
60 | * @return false if the handler wants to stop parsing after return.
61 | * @throws ParseException
62 | *
63 | * @see #startObject
64 | */
65 | boolean endObject() throws ParseException, IOException;
66 |
67 | /**
68 | * Receive notification of the beginning of a JSON object entry.
69 | *
70 | * @param key
71 | * - Key of a JSON object entry.
72 | *
73 | * @return false if the handler wants to stop parsing after return.
74 | * @throws ParseException
75 | *
76 | * @see #endObjectEntry
77 | */
78 | boolean startObjectEntry(String key) throws ParseException, IOException;
79 |
80 | /**
81 | * Receive notification of the end of the value of previous object entry.
82 | *
83 | * @return false if the handler wants to stop parsing after return.
84 | * @throws ParseException
85 | *
86 | * @see #startObjectEntry
87 | */
88 | boolean endObjectEntry() throws ParseException, IOException;
89 |
90 | /**
91 | * Receive notification of the beginning of a JSON array.
92 | *
93 | * @return false if the handler wants to stop parsing after return.
94 | * @throws ParseException
95 | *
96 | * @see #endArray
97 | */
98 | boolean startArray() throws ParseException, IOException;
99 |
100 | /**
101 | * Receive notification of the end of a JSON array.
102 | *
103 | * @return false if the handler wants to stop parsing after return.
104 | * @throws ParseException
105 | *
106 | * @see #startArray
107 | */
108 | boolean endArray() throws ParseException, IOException;
109 |
110 | /**
111 | * Receive notification of the JSON primitive values: java.lang.String,
112 | * java.lang.Number, java.lang.Boolean null
113 | *
114 | * @param value
115 | * - Instance of the following: java.lang.String,
116 | * java.lang.Number, java.lang.Boolean null
117 | *
118 | * @return false if the handler wants to stop parsing after return.
119 | * @throws ParseException
120 | */
121 | boolean primitive(Object value) throws ParseException, IOException;
122 |
123 | }
124 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/ContentHandlerCompressor.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.IOException;
19 |
20 | import net.minidev.json.JSONStyle;
21 | import net.minidev.json.JSONValue;
22 |
23 | public class ContentHandlerCompressor implements ContentHandler {
24 | Appendable out;
25 | JSONStyle compression;
26 |
27 | int[] stack = new int[10];
28 | int pos;
29 |
30 | // push 0 = < Object
31 | // push 1 = < Array
32 | private void push(int type) {
33 | pos += 2;
34 | if (pos >= stack.length) {
35 | int[] tmp = new int[stack.length * 2];
36 | System.arraycopy(stack, 0, tmp, 0, stack.length);
37 | stack = tmp;
38 | }
39 | stack[pos] = type;
40 | stack[pos + 1] = 0;
41 | }
42 |
43 | private boolean isInObject() {
44 | return stack[pos] == 0;
45 | }
46 |
47 | private boolean isInArray() {
48 | return stack[pos] == 1;
49 | }
50 |
51 | public ContentHandlerCompressor(Appendable out, JSONStyle compression) {
52 | this.out = out;
53 | this.compression = compression;
54 | }
55 |
56 | // @Override JDK 1.5 compatibility change
57 | public void startJSON() throws ParseException, IOException {
58 | }
59 |
60 | // @Override JDK 1.5 compatibility change
61 | public void endJSON() throws ParseException, IOException {
62 | }
63 |
64 | // @Override JDK 1.5 compatibility change
65 | public boolean startObject() throws ParseException, IOException {
66 | if (isInArray() && stack[pos + 1]++ > 0)
67 | out.append(',');
68 | out.append('{');
69 | push(0);
70 | // stack.add(JsonStructure.newObj());
71 | return false;
72 | }
73 |
74 | // @Override JDK 1.5 compatibility change
75 | public boolean endObject() throws ParseException, IOException {
76 | out.append('}');
77 | pos -= 2;
78 | // stack.pop();
79 | return false;
80 | }
81 |
82 | // @Override JDK 1.5 compatibility change
83 | public boolean startObjectEntry(String key) throws ParseException, IOException {
84 | if (stack[pos + 1]++ > 0)
85 | out.append(',');
86 | if (key == null)
87 | out.append("null");
88 | else if (!compression.mustProtectKey(key))
89 | out.append(key);
90 | else {
91 | out.append('"');
92 | JSONValue.escape(key, out, compression);
93 | out.append('"');
94 | }
95 | out.append(':');
96 | return false;
97 | }
98 |
99 | // @Override JDK 1.5 compatibility change
100 | public boolean endObjectEntry() throws ParseException, IOException {
101 | return false;
102 | }
103 |
104 | // @Override JDK 1.5 compatibility change
105 | public boolean startArray() throws ParseException, IOException {
106 | if (isInArray() && stack[pos + 1]++ > 0)
107 | out.append(',');
108 | out.append('[');
109 | push(1);
110 | return false;
111 | }
112 |
113 | // @Override JDK 1.5 compatibility change
114 | public boolean endArray() throws ParseException, IOException {
115 | out.append(']');
116 | pos -= 2;
117 | return false;
118 | }
119 |
120 | // @Override JDK 1.5 compatibility change
121 | public boolean primitive(Object value) throws ParseException, IOException {
122 | if (!isInObject() && stack[pos + 1]++ > 0)
123 | out.append(',');
124 |
125 | if (value instanceof String) {
126 | compression.writeString(out, (String) value);
127 | } else
128 | JSONValue.writeJSONString(value, out, compression);
129 | return false;
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/ContentHandlerDumy.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.IOException;
19 |
20 | public class ContentHandlerDumy implements ContentHandler {
21 | public static ContentHandlerDumy HANDLER = new ContentHandlerDumy();
22 |
23 | // @Override JDK 1.5 compatibility change
24 | public void startJSON() throws ParseException {
25 | }
26 |
27 | // @Override JDK 1.5 compatibility change
28 | public void endJSON() throws ParseException {
29 | }
30 |
31 | // @Override JDK 1.5 compatibility change
32 | public boolean startObject() throws ParseException, IOException {
33 | return false;
34 | }
35 |
36 | // @Override JDK 1.5 compatibility change
37 | public boolean endObject() throws ParseException {
38 | return false;
39 | }
40 |
41 | // @Override JDK 1.5 compatibility change
42 | public boolean startObjectEntry(String key) throws ParseException {
43 | return false;
44 | }
45 |
46 | // @Override JDK 1.5 compatibility change
47 | public boolean endObjectEntry() throws ParseException {
48 | return false;
49 | }
50 |
51 | // @Override JDK 1.5 compatibility change
52 | public boolean startArray() throws ParseException {
53 | return false;
54 | }
55 |
56 | // @Override JDK 1.5 compatibility change
57 | public boolean endArray() throws ParseException {
58 | return false;
59 | }
60 |
61 | // @Override JDK 1.5 compatibility change
62 | public boolean primitive(Object value) throws ParseException {
63 | return false;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/FakeContainerFactory.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.util.AbstractMap;
19 | import java.util.ArrayList;
20 | import java.util.List;
21 | import java.util.Map;
22 | import java.util.Set;
23 |
24 | /**
25 | * Fake Container factory used for JSon check and SaX parsing
26 | *
27 | * @author Uriel Chemouni
28 | */
29 | public class FakeContainerFactory implements ContainerFactory {
30 | public FackList list;
31 | public FackMap map;
32 |
33 | // @Override JDK 1.5 compatibility change
34 | public List createArrayContainer() {
35 | if (list == null)
36 | list = new FackList();
37 | return list;
38 | }
39 |
40 | // @Override JDK 1.5 compatibility change
41 | public Map createObjectContainer() {
42 | if (map == null)
43 | map = new FackMap();
44 | return map;
45 | }
46 |
47 | /**
48 | * dummy AbstractMap
49 | */
50 | static class FackMap extends AbstractMap {
51 | public Object put(String key, Object value) {
52 | return null;
53 | }
54 |
55 | @Override
56 | public Set> entrySet() {
57 | return null;
58 | }
59 | }
60 |
61 | /**
62 | * dummy AbstractList
63 | * replace AbsractList by list to make it compile on jdk 1.7
64 | */
65 | @SuppressWarnings("serial")
66 | static class FackList extends ArrayList {
67 | public boolean add(Object e) {
68 | return false;
69 | }
70 |
71 | @Override
72 | public Object get(int index) {
73 | return null;
74 | }
75 |
76 | @Override
77 | public int size() {
78 | return 0;
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/JSONParser.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.InputStream;
19 | import java.io.Reader;
20 | import java.io.UnsupportedEncodingException;
21 |
22 | public class JSONParser {
23 | /**
24 | * allow simple quote as String quoting char
25 | */
26 | public final static int ACCEPT_SIMPLE_QUOTE = 1;
27 | /**
28 | * allow non quoted test
29 | */
30 | public final static int ACCEPT_NON_QUOTE = 2;
31 | /**
32 | * Parse NaN as Float.NaN
33 | */
34 | public final static int ACCEPT_NAN = 4;
35 | /**
36 | * Ignore control char in input text.
37 | */
38 | public final static int IGNORE_CONTROL_CHAR = 8;
39 | /**
40 | * Use int datatype to store number when it's possible.
41 | *
42 | * @since 1.0.7
43 | */
44 | public final static int USE_INTEGER_STORAGE = 16;
45 | /**
46 | * Throws exception on excessive 0 leading in digits
47 | *
48 | * @since 1.0.7
49 | */
50 | public final static int ACCEPT_LEADING_ZERO = 32;
51 | /**
52 | * Throws exception on useless comma in object and array
53 | *
54 | * @since 1.0.8
55 | */
56 | public final static int ACCEPT_USELESS_COMMA = 64;
57 | /**
58 | * Allow Json-smart to use Double or BigDecimal to store floating point
59 | * value
60 | *
61 | * You may need to disable HI_PRECISION_FLOAT feature on 32bit to improve
62 | * parsing performances.
63 | *
64 | * @since 1.0.9
65 | */
66 | public final static int USE_HI_PRECISION_FLOAT = 128;
67 | /**
68 | * If enabled json-smart will throws exception if datas are present after
69 | * the end of the Json data.
70 | *
71 | * @since 1.0.9-2
72 | */
73 | public final static int ACCEPT_TAILLING_DATA = 256;
74 | /**
75 | * smart mode, fastest parsing mode. accept lots of non standard json syntax
76 | *
77 | * @since 1.3.1
78 | */
79 | public final static int ACCEPT_TAILLING_SPACE = 512;
80 | /**
81 | * smart mode, fastest parsing mode. accept lots of non standard json syntax
82 | *
83 | * @since 1.0.6
84 | */
85 | public final static int MODE_PERMISSIVE = -1;
86 | /**
87 | * strict RFC4627 mode.
88 | *
89 | * slower than PERMISIF MODE.
90 | *
91 | * @since 1.0.6
92 | */
93 | public final static int MODE_RFC4627 = USE_INTEGER_STORAGE | USE_HI_PRECISION_FLOAT | ACCEPT_TAILLING_DATA;
94 | /**
95 | * Parse Object like json-simple
96 | *
97 | * Best for an iso-bug json-simple API port.
98 | *
99 | * @since 1.0.7
100 | */
101 | public final static int MODE_JSON_SIMPLE = ACCEPT_USELESS_COMMA | USE_HI_PRECISION_FLOAT | ACCEPT_TAILLING_DATA | ACCEPT_TAILLING_SPACE;
102 | /**
103 | * Strictest parsing mode
104 | *
105 | * @since 1.0.9-2
106 | */
107 | public final static int MODE_STRICTEST = USE_INTEGER_STORAGE | USE_HI_PRECISION_FLOAT;
108 | /**
109 | * Default json-smart processing mode
110 | */
111 | public static int DEFAULT_PERMISSIVE_MODE = (System.getProperty("JSON_SMART_SIMPLE") != null) ? MODE_JSON_SIMPLE
112 | : MODE_PERMISSIVE;
113 |
114 | /*
115 | * internal fields
116 | */
117 | private int mode;
118 | private JSONParserReader pStream;
119 | private JSONParserInputStream pSBintream;
120 | private JSONParserString pString;
121 | private JSONParserByteArray pBytes;
122 |
123 | /**
124 | * @deprecated prefer usage of new JSONParser(JSONParser.MODE_*)
125 | */
126 | public JSONParser() {
127 | this.mode = DEFAULT_PERMISSIVE_MODE;
128 | }
129 |
130 | public JSONParser(int permissifMode) {
131 | this.mode = permissifMode;
132 | }
133 |
134 | /**
135 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
136 | * generated by a ContainerFactory
137 | */
138 | public Object parse(String in) throws ParseException {
139 | if (pString == null)
140 | pString = new JSONParserString(mode);
141 | return pString.parse(in);
142 | }
143 |
144 | /**
145 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
146 | * generated by a ContainerFactory
147 | */
148 | public Object parse(String in, ContainerFactory containerFactory) throws ParseException {
149 | if (pString == null)
150 | pString = new JSONParserString(mode);
151 | return pString.parse(in, containerFactory);
152 | }
153 |
154 | public Object parse(String in, ContainerFactory containerFactory, ContentHandler handler) throws ParseException {
155 | if (pString == null)
156 | pString = new JSONParserString(mode);
157 | return pString.parse(in, containerFactory, handler);
158 | }
159 |
160 | /**
161 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
162 | * generated by a ContainerFactory
163 | */
164 | public Object parse(byte[] in) throws ParseException {
165 | if (pBytes == null)
166 | pBytes = new JSONParserByteArray(mode);
167 | return pBytes.parse(in);
168 | }
169 |
170 | /**
171 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
172 | * generated by a ContainerFactory
173 | */
174 | public Object parse(byte[] in, ContainerFactory containerFactory) throws ParseException {
175 | if (pBytes == null)
176 | pBytes = new JSONParserByteArray(mode);
177 | return pBytes.parse(in, containerFactory);
178 | }
179 |
180 | public Object parse(byte[] in, ContainerFactory containerFactory, ContentHandler handler) throws ParseException {
181 | if (pBytes == null)
182 | pBytes = new JSONParserByteArray(mode);
183 | return pBytes.parse(in, containerFactory, handler);
184 | }
185 |
186 | public Object parse(byte[] in, int offset, int length) throws ParseException {
187 | if (pBytes == null)
188 | pBytes = new JSONParserByteArray(mode);
189 | return pBytes.parse(in, offset, length, ContainerFactory.FACTORY_SIMPLE, ContentHandlerDumy.HANDLER);
190 | }
191 |
192 | public Object parse(byte[] in, int offset, int length, ContainerFactory containerFactory) throws ParseException {
193 | if (pBytes == null)
194 | pBytes = new JSONParserByteArray(mode);
195 | return pBytes.parse(in, offset, length, containerFactory, ContentHandlerDumy.HANDLER);
196 | }
197 |
198 | public Object parse(byte[] in, int offset, int length, ContainerFactory containerFactory, ContentHandler handler)
199 | throws ParseException {
200 | if (pBytes == null)
201 | pBytes = new JSONParserByteArray(mode);
202 | return pBytes.parse(in, offset, length, containerFactory, handler);
203 | }
204 |
205 | /**
206 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
207 | * generated by a ContainerFactory
208 | */
209 | public Object parse(Reader in) throws ParseException {
210 | if (pStream == null)
211 | pStream = new JSONParserReader(mode);
212 | return pStream.parse(in);
213 | }
214 |
215 | /**
216 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
217 | * generated by a ContainerFactory
218 | */
219 | public Object parse(Reader in, ContainerFactory containerFactory) throws ParseException {
220 | if (pStream == null)
221 | pStream = new JSONParserReader(mode);
222 | return pStream.parse(in, containerFactory);
223 | }
224 |
225 | /**
226 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
227 | * generated by a ContainerFactory
228 | */
229 | public Object parse(Reader in, ContainerFactory containerFactory, ContentHandler handler) throws ParseException {
230 | if (pStream == null)
231 | pStream = new JSONParserReader(mode);
232 | return pStream.parse(in, containerFactory, handler);
233 | }
234 |
235 | /**
236 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
237 | * generated by a ContainerFactory
238 | */
239 | public Object parse(InputStream in) throws ParseException, UnsupportedEncodingException {
240 | if (pSBintream == null)
241 | pSBintream = new JSONParserInputStream(mode);
242 | return pSBintream.parse(in);
243 | }
244 |
245 | /**
246 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
247 | * generated by a ContainerFactory
248 | */
249 | public Object parse(InputStream in, ContainerFactory containerFactory) throws ParseException, UnsupportedEncodingException {
250 | if (pSBintream == null)
251 | pSBintream = new JSONParserInputStream(mode);
252 | return pSBintream.parse(in, containerFactory);
253 | }
254 |
255 | /**
256 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
257 | * generated by a ContainerFactory
258 | */
259 | public Object parse(InputStream in, ContainerFactory containerFactory, ContentHandler handler)
260 | throws ParseException, UnsupportedEncodingException {
261 | if (pSBintream == null)
262 | pSBintream = new JSONParserInputStream(mode);
263 | return pSBintream.parse(in, containerFactory, handler);
264 | }
265 |
266 | }
267 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/JSONParserByteArray.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF;
19 |
20 | /**
21 | * Parser for JSON text. Please note that JSONParser is NOT thread-safe.
22 | *
23 | * @author Uriel Chemouni
24 | */
25 | class JSONParserByteArray extends JSONParserMemory {
26 | private byte[] in;
27 |
28 | public JSONParserByteArray(int permissiveMode) {
29 | super(permissiveMode);
30 | }
31 |
32 | /**
33 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
34 | * generated by a ContainerFactory
35 | */
36 | public Object parse(byte[] in) throws ParseException {
37 | return parse(in, ContainerFactory.FACTORY_SIMPLE, ContentHandlerDumy.HANDLER);
38 | }
39 |
40 | /**
41 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
42 | * generated by a ContainerFactory
43 | */
44 | public Object parse(byte[] in, ContainerFactory containerFactory) throws ParseException {
45 | return parse(in, containerFactory, ContentHandlerDumy.HANDLER);
46 | }
47 |
48 | /**
49 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
50 | * generated by a ContainerFactory
51 | */
52 | public Object parse(byte[] in, ContainerFactory containerFactory, ContentHandler handler) throws ParseException {
53 | this.in = in;
54 | this.len = in.length;
55 | this.pos = -1;
56 | return parse(containerFactory, handler);
57 | }
58 |
59 | /**
60 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
61 | * generated by a ContainerFactory
62 | *
63 | *
64 | * Processing from offset position until length
65 | */
66 | public Object parse(byte[] in, int offset, int length, ContainerFactory containerFactory, ContentHandler handler)
67 | throws ParseException {
68 | this.in = in;
69 | this.len = length;
70 | this.pos = offset - 1;
71 | return parse(containerFactory, handler);
72 | }
73 |
74 | protected void extractString(int beginIndex, int endIndex) {
75 | xs = new String(in, beginIndex, endIndex - beginIndex);
76 | }
77 |
78 | protected int indexOf(char c, int pos) {
79 | for (int i = pos; i < len; i++)
80 | if (in[i] == (byte) c)
81 | return i;
82 | return -1;
83 | }
84 |
85 | protected void read() {
86 | if (++pos >= len)
87 | this.c = EOI;
88 | else
89 | this.c = (char) in[pos];
90 | }
91 |
92 | /**
93 | * Same as read() in memory parsing
94 | */
95 | protected void readS() {
96 | if (++pos >= len)
97 | this.c = EOI;
98 | else
99 | this.c = (char) in[pos];
100 | }
101 |
102 | protected void readNoEnd() throws ParseException {
103 | if (++pos >= len) {
104 | this.c = EOI;
105 | throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF");
106 | } else
107 | this.c = (char) in[pos];
108 | }
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/JSONParserInputStream.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import java.io.InputStream;
19 | import java.io.InputStreamReader;
20 | import java.io.UnsupportedEncodingException;
21 |
22 | /**
23 | * Parser for JSON text. Please note that JSONParser is NOT thread-safe.
24 | *
25 | * @author Uriel Chemouni
26 | */
27 | class JSONParserInputStream extends JSONParserReader {
28 | // len
29 | public JSONParserInputStream(int permissiveMode) {
30 | super(permissiveMode);
31 | }
32 |
33 | /**
34 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
35 | * generated by a ContainerFactory
36 | */
37 | public Object parse(InputStream in) throws ParseException, UnsupportedEncodingException {
38 | return parse(in, ContainerFactory.FACTORY_SIMPLE, ContentHandlerDumy.HANDLER);
39 | }
40 |
41 | /**
42 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
43 | * generated by a ContainerFactory
44 | */
45 | public Object parse(InputStream in, ContainerFactory containerFactory) throws ParseException, UnsupportedEncodingException {
46 | return parse(in, containerFactory, ContentHandlerDumy.HANDLER);
47 | }
48 |
49 | /**
50 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
51 | * generated by a ContainerFactory
52 | * @throws UnsupportedEncodingException
53 | */
54 | public Object parse(InputStream in, ContainerFactory containerFactory, ContentHandler handler)
55 | throws ParseException, UnsupportedEncodingException {
56 | InputStreamReader i2 = new InputStreamReader(in, "utf8");
57 | this.pos = -1;
58 | return super.parse(i2, containerFactory, handler);
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/JSONParserMemory.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_CHAR;
19 | import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF;
20 | import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_TOKEN;
21 |
22 | import java.io.IOException;
23 |
24 | /**
25 | * Parser for JSON text. Please note that JSONParser is NOT thread-safe.
26 | *
27 | * @author Uriel Chemouni
28 | * @see JSONParserString
29 | * @see JSONParserByteArray
30 | */
31 | abstract class JSONParserMemory extends JSONParserBase {
32 | protected int len;
33 |
34 | public JSONParserMemory(int permissiveMode) {
35 | super(permissiveMode);
36 | }
37 |
38 | protected void readNQString(boolean[] stop) throws IOException {
39 | int start = pos;
40 | skipNQString(stop);
41 | extractStringTrim(start, pos);
42 | }
43 |
44 | protected Object readNumber(boolean[] stop) throws ParseException, IOException {
45 | int start = pos;
46 | // accept first char digit or -
47 | read();
48 | skipDigits();
49 |
50 | // Integer digit
51 | if (c != '.' && c != 'E' && c != 'e') {
52 | skipSpace();
53 | if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) {
54 | // convert string
55 | skipNQString(stop);
56 | extractStringTrim(start, pos);
57 | if (!acceptNonQuote)
58 | throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs);
59 | return xs;
60 | }
61 | extractStringTrim(start, pos);
62 | return parseNumber(xs);
63 | }
64 | // floating point
65 | if (c == '.') {
66 | //
67 | read();
68 | skipDigits();
69 | }
70 | if (c != 'E' && c != 'e') {
71 | skipSpace();
72 | if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) {
73 | // convert string
74 | skipNQString(stop);
75 | extractStringTrim(start, pos);
76 | if (!acceptNonQuote)
77 | throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs);
78 | return xs;
79 | }
80 | extractStringTrim(start, pos);
81 | return extractFloat();
82 | }
83 | sb.append('E');
84 | read();
85 | if (c == '+' || c == '-' || c >= '0' && c <= '9') {
86 | sb.append(c);
87 | read(); // skip first char
88 | skipDigits();
89 | skipSpace();
90 | if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) {
91 | // convert string
92 | skipNQString(stop);
93 | extractStringTrim(start, pos);
94 | if (!acceptNonQuote)
95 | throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs);
96 | return xs;
97 | }
98 | extractStringTrim(start, pos);
99 | return extractFloat();
100 | } else {
101 | skipNQString(stop);
102 | extractStringTrim(start, pos);
103 | if (!acceptNonQuote)
104 | throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs);
105 | if (!acceptLeadinZero)
106 | checkLeadinZero();
107 | return xs;
108 | }
109 | // throw new ParseException(pos - 1, ERROR_UNEXPECTED_CHAR, null);
110 | }
111 |
112 | protected void readString() throws ParseException, IOException {
113 | if (!acceptSimpleQuote && c == '\'') {
114 | if (acceptNonQuote) {
115 | readNQString(stopAll);
116 | return;
117 | }
118 | throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c);
119 | }
120 | int tmpP = indexOf(c, pos + 1);
121 | if (tmpP == -1)
122 | throw new ParseException(len, ERROR_UNEXPECTED_EOF, null);
123 | extractString(pos + 1, tmpP);
124 | if (xs.indexOf('\\') == -1) {
125 | checkControleChar();
126 | pos = tmpP;
127 | read();
128 | // handler.primitive(tmp);
129 | return;
130 | }
131 | sb.clear();
132 | readString2();
133 | }
134 |
135 | abstract protected void extractString(int start, int stop);
136 |
137 | abstract protected int indexOf(char c, int pos);
138 |
139 | protected void extractStringTrim(int start, int stop) {
140 | extractString(start, stop);
141 | xs = xs.trim();
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/JSONParserReader.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF;
19 |
20 | import java.io.IOException;
21 | import java.io.Reader;
22 |
23 | /**
24 | * Parser for JSON text. Please note that JSONParser is NOT thread-safe.
25 | *
26 | * @author Uriel Chemouni
27 | */
28 | class JSONParserReader extends JSONParserStream {
29 | private Reader in;
30 |
31 | // len
32 | public JSONParserReader(int permissiveMode) {
33 | super(permissiveMode);
34 | }
35 |
36 | /**
37 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
38 | * generated by a ContainerFactory
39 | */
40 | public Object parse(Reader in) throws ParseException {
41 | return parse(in, ContainerFactory.FACTORY_SIMPLE, ContentHandlerDumy.HANDLER);
42 | }
43 |
44 | /**
45 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
46 | * generated by a ContainerFactory
47 | */
48 | public Object parse(Reader in, ContainerFactory containerFactory) throws ParseException {
49 | return parse(in, containerFactory, ContentHandlerDumy.HANDLER);
50 | }
51 |
52 | /**
53 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
54 | * generated by a ContainerFactory
55 | */
56 | public Object parse(Reader in, ContainerFactory containerFactory, ContentHandler handler) throws ParseException {
57 | //
58 | this.in = in;
59 | this.pos = -1;
60 | return super.parse(containerFactory, handler);
61 | }
62 |
63 | protected void read() throws IOException {
64 | int i = in.read();
65 | c = (i == -1) ? (char) EOI : (char) i;
66 | pos++;
67 | //
68 | }
69 |
70 | protected void readS() throws IOException {
71 | sb.append(c);
72 | int i = in.read();
73 | if (i == -1) {
74 | c = EOI;
75 | } else {
76 | c = (char) i;
77 | pos++;
78 | }
79 | }
80 |
81 | protected void readNoEnd() throws ParseException, IOException {
82 | int i = in.read();
83 | if (i == -1)
84 | throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF");
85 | c = (char) i;
86 | //
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/JSONParserStream.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_CHAR;
19 | import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_TOKEN;
20 |
21 | import java.io.IOException;
22 |
23 | /**
24 | * Parser for JSON text. Please note that JSONParser is NOT thread-safe.
25 | *
26 | * @author Uriel Chemouni
27 | * @see JSONParserInputStream
28 | * @see JSONParserReader
29 | */
30 | abstract class JSONParserStream extends JSONParserBase {
31 | // len
32 | //
33 | public JSONParserStream(int permissiveMode) {
34 | super(permissiveMode);
35 | }
36 |
37 | protected void readNQString(boolean[] stop) throws IOException {
38 | sb.clear();
39 | skipNQString(stop);
40 | xs = sb.toString().trim();
41 | }
42 |
43 | protected Object readNumber(boolean[] stop) throws ParseException, IOException {
44 | sb.clear();
45 | sb.append(c);// accept first char digit or -
46 | read();
47 | skipDigits();
48 |
49 | // Integer digit
50 | if (c != '.' && c != 'E' && c != 'e') {
51 | skipSpace();
52 | if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) {
53 | // convert string
54 | skipNQString(stop);
55 | xs = sb.toString().trim();
56 | if (!acceptNonQuote)
57 | throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs);
58 | return xs;
59 | }
60 | xs = sb.toString().trim();
61 | return parseNumber(xs);
62 | }
63 | // floating point
64 | if (c == '.') {
65 | sb.append(c);
66 | read();
67 | skipDigits();
68 | }
69 | if (c != 'E' && c != 'e') {
70 | skipSpace();
71 | if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) {
72 | // convert string
73 | skipNQString(stop);
74 | xs = sb.toString().trim();
75 | if (!acceptNonQuote)
76 | throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs);
77 | return xs;
78 | }
79 | xs = sb.toString().trim();
80 | return extractFloat();
81 | }
82 | sb.append('E');
83 | read();
84 | if (c == '+' || c == '-' || c >= '0' && c <= '9') {
85 | sb.append(c);
86 | read(); // skip first char
87 | skipDigits();
88 | skipSpace();
89 | if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) {
90 | // convert string
91 | skipNQString(stop);
92 | xs = sb.toString().trim();
93 | if (!acceptNonQuote)
94 | throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs);
95 | return xs;
96 | }
97 | xs = sb.toString().trim();
98 | return extractFloat();
99 | } else {
100 | skipNQString(stop);
101 | xs = sb.toString().trim();
102 | if (!acceptNonQuote)
103 | throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs);
104 | if (!acceptLeadinZero)
105 | checkLeadinZero();
106 | return xs;
107 | }
108 | // throw new ParseException(pos - 1, ERROR_UNEXPECTED_CHAR, null);
109 | }
110 |
111 | protected void readString() throws ParseException, IOException {
112 | if (!acceptSimpleQuote && c == '\'') {
113 | if (acceptNonQuote) {
114 | readNQString(stopAll);
115 | return;
116 | }
117 | throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c);
118 | }
119 | sb.clear();
120 | //
121 | //
122 | //
123 | //
124 | //
125 | //
126 | //
127 | //
128 | //
129 | //
130 | /* assert (c == '\"' || c == '\'') */
131 | readString2();
132 | }
133 |
134 | //
135 | //
136 | //
137 | //
138 | //
139 | //
140 | //
141 | //
142 | }
143 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/JSONParserString.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF;
19 |
20 | /**
21 | * Parser for JSON text. Please note that JSONParser is NOT thread-safe.
22 | *
23 | * @author Uriel Chemouni
24 | */
25 | class JSONParserString extends JSONParserMemory {
26 | private String in;
27 |
28 | public JSONParserString(int permissiveMode) {
29 | super(permissiveMode);
30 | }
31 |
32 | /**
33 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
34 | * generated by a ContainerFactory
35 | */
36 | public Object parse(String in) throws ParseException {
37 | return parse(in, ContainerFactory.FACTORY_SIMPLE, ContentHandlerDumy.HANDLER);
38 | }
39 |
40 | /**
41 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
42 | * generated by a ContainerFactory
43 | */
44 | public Object parse(String in, ContainerFactory containerFactory) throws ParseException {
45 | return parse(in, containerFactory, ContentHandlerDumy.HANDLER);
46 | }
47 |
48 | /**
49 | * use to return Primitive Type, or String, Or JsonObject or JsonArray
50 | * generated by a ContainerFactory
51 | */
52 | public Object parse(String in, ContainerFactory containerFactory, ContentHandler handler) throws ParseException {
53 | this.in = in;
54 | this.len = in.length();
55 | this.pos = -1;
56 | return parse(containerFactory, handler);
57 | }
58 |
59 | protected void extractString(int beginIndex, int endIndex) {
60 | xs = in.substring(beginIndex, endIndex);
61 | }
62 |
63 | protected int indexOf(char c, int pos) {
64 | return in.indexOf(c, pos);
65 | }
66 | /**
67 | * Read next char or END OF INPUT
68 | */
69 | protected void read() {
70 | if (++pos >= len)
71 | this.c = EOI;
72 | else
73 | this.c = in.charAt(pos);
74 | }
75 |
76 | /**
77 | * Same as read() in memory parsing
78 | */
79 | protected void readS() {
80 | if (++pos >= len)
81 | this.c = EOI;
82 | else
83 | this.c = in.charAt(pos);
84 | }
85 | /**
86 | * read data can not be EOI
87 | */
88 | protected void readNoEnd() throws ParseException {
89 | if (++pos >= len) {
90 | this.c = EOI;
91 | throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF");
92 | } else
93 | this.c = in.charAt(pos);
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/parser/ParseException.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.parser;
2 |
3 | /*
4 | * Copyright 2011 JSON-SMART authors
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | /**
19 | * ParseException explains why and where the error occurs in source JSON text.
20 | *
21 | * @author Uriel Chemouni
22 | */
23 | public class ParseException extends Exception {
24 | private static final long serialVersionUID = 8879024178584091857L;
25 |
26 | public static final int ERROR_UNEXPECTED_CHAR = 0;
27 | public static final int ERROR_UNEXPECTED_TOKEN = 1;
28 | public static final int ERROR_UNEXPECTED_EXCEPTION = 2;
29 | public static final int ERROR_UNEXPECTED_EOF = 3;
30 | public static final int ERROR_UNEXPECTED_UNICODE = 4;
31 | public static final int ERROR_UNEXPECTED_DUPLICATE_KEY = 5;
32 | public static final int ERROR_UNEXPECTED_LEADING_0 = 6;
33 |
34 | private int errorType;
35 | private Object unexpectedObject;
36 | private int position;
37 |
38 | public ParseException(int position, int errorType, Object unexpectedObject) {
39 | super(toMessage(position, errorType, unexpectedObject));
40 | this.position = position;
41 | this.errorType = errorType;
42 | this.unexpectedObject = unexpectedObject;
43 | }
44 |
45 | public ParseException(int position, Throwable cause) {
46 | super(toMessage(position, ERROR_UNEXPECTED_EXCEPTION, cause), cause);
47 | this.position = position;
48 | this.errorType = ERROR_UNEXPECTED_EXCEPTION;
49 | this.unexpectedObject = cause;
50 | }
51 |
52 | public int getErrorType() {
53 | return errorType;
54 | }
55 |
56 | /**
57 | * @return The character position (starting with 0) of the input where the
58 | * error occurs.
59 | */
60 | public int getPosition() {
61 | return position;
62 | }
63 |
64 | /**
65 | * @return One of the following base on the value of errorType:
66 | * ERROR_UNEXPECTED_CHAR java.lang.Character ERROR_UNEXPECTED_TOKEN
67 | * ERROR_UNEXPECTED_EXCEPTION java.lang.Exception
68 | */
69 | public Object getUnexpectedObject() {
70 | return unexpectedObject;
71 | }
72 |
73 | private static String toMessage(int position, int errorType, Object unexpectedObject) {
74 | StringBuilder sb = new StringBuilder();
75 |
76 | if (errorType == ERROR_UNEXPECTED_CHAR) {
77 | sb.append("Unexpected character (");
78 | sb.append(unexpectedObject);
79 | sb.append(") at position ");
80 | sb.append(position);
81 | sb.append(".");
82 | } else if (errorType == ERROR_UNEXPECTED_TOKEN) {
83 | sb.append("Unexpected token ");
84 | sb.append(unexpectedObject);
85 | sb.append(" at position ");
86 | sb.append(position);
87 | sb.append(".");
88 | } else if (errorType == ERROR_UNEXPECTED_EXCEPTION) {
89 | sb.append("Unexpected exception ");
90 | sb.append(unexpectedObject);
91 | sb.append(" occur at position ");
92 | sb.append(position);
93 | sb.append(".");
94 | } else if (errorType == ERROR_UNEXPECTED_EOF) {
95 | sb.append("Unexpected End Of File position ");
96 | sb.append(position);
97 | sb.append(": ");
98 | sb.append(unexpectedObject);
99 | } else if (errorType == ERROR_UNEXPECTED_UNICODE) {
100 | sb.append("Unexpected unicode escape sequence ");
101 | sb.append(unexpectedObject);
102 | sb.append(" at position ");
103 | sb.append(position);
104 | sb.append(".");
105 | } else if (errorType == ERROR_UNEXPECTED_DUPLICATE_KEY) {
106 | sb.append("Unexpected duplicate key:");
107 | sb.append(unexpectedObject);
108 | sb.append(" at position ");
109 | sb.append(position);
110 | sb.append(".");
111 | } else if (errorType == ERROR_UNEXPECTED_LEADING_0) {
112 | sb.append("Unexpected leading 0 in digit for token:");
113 | sb.append(unexpectedObject);
114 | sb.append(" at position ");
115 | sb.append(position);
116 | sb.append(".");
117 | } else {
118 | sb.append("Unkown error at position ");
119 | sb.append(position);
120 | sb.append(".");
121 | }
122 | return sb.toString();
123 | }
124 |
125 | }
126 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/reader/ArrayWriter.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.reader;
2 |
3 | import java.io.IOException;
4 |
5 | import net.minidev.json.JSONStyle;
6 | import net.minidev.json.JSONValue;
7 |
8 | public class ArrayWriter implements JsonWriterI {
9 | public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException {
10 | compression.arrayStart(out);
11 | boolean needSep = false;
12 | for (Object o : ((Object[]) value)) {
13 | if (needSep)
14 | compression.objectNext(out);
15 | else
16 | needSep = true;
17 | JSONValue.writeJSONString(o, out, compression);
18 | }
19 | compression.arrayStop(out);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/reader/BeansWriter.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.reader;
2 |
3 | import java.io.IOException;
4 | import java.lang.reflect.Field;
5 | import java.lang.reflect.Method;
6 | import java.lang.reflect.Modifier;
7 |
8 | import net.minidev.json.JSONStyle;
9 | import net.minidev.json.JSONUtil;
10 |
11 | public class BeansWriter implements JsonWriterI {
12 | public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException {
13 | try {
14 | Class> nextClass = value.getClass();
15 | boolean needSep = false;
16 | compression.objectStart(out);
17 | while (nextClass != Object.class) {
18 | Field[] fields = nextClass.getDeclaredFields();
19 | for (Field field : fields) {
20 | int m = field.getModifiers();
21 | if ((m & (Modifier.STATIC | Modifier.TRANSIENT | Modifier.FINAL)) > 0)
22 | continue;
23 | Object v = null;
24 | if ((m & Modifier.PUBLIC) > 0) {
25 | v = field.get(value);
26 | } else {
27 | String g = JSONUtil.getGetterName(field.getName());
28 | Method mtd = null;
29 |
30 | try {
31 | mtd = nextClass.getDeclaredMethod(g);
32 | } catch (Exception e) {
33 | }
34 | if (mtd == null) {
35 | Class> c2 = field.getType();
36 | if (c2 == Boolean.TYPE || c2 == Boolean.class) {
37 | g = JSONUtil.getIsName(field.getName());
38 | mtd = nextClass.getDeclaredMethod(g);
39 | }
40 | }
41 | if (mtd == null)
42 | continue;
43 | v = mtd.invoke(value);
44 | }
45 | if (v == null && compression.ignoreNull())
46 | continue;
47 | if (needSep)
48 | compression.objectNext(out);
49 | else
50 | needSep = true;
51 | String key = field.getName();
52 |
53 | JsonWriter.writeJSONKV(key, v, out, compression);
54 | // compression.objectElmStop(out);
55 | }
56 | nextClass = nextClass.getSuperclass();
57 | }
58 | compression.objectStop(out);
59 | } catch (Exception e) {
60 | throw new RuntimeException(e);
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/json-smart/src/main/java/net/minidev/json/reader/JsonWriterI.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.reader;
2 |
3 | import java.io.IOException;
4 |
5 | import net.minidev.json.JSONStyle;
6 |
7 | public interface JsonWriterI {
8 | public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException;
9 | }
10 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/BugReport.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONObject;
5 | import net.minidev.json.JSONStyle;
6 | import net.minidev.json.JSONValue;
7 |
8 | public class BugReport extends TestCase {
9 |
10 | public void testIssue41() throws Exception {
11 | String test;
12 | test = "[{ 'Key' : [{''K2':['tab1']}]}]";
13 | test = test.replace('\'', '"');
14 | assertEquals(JSONValue.isValidJson(test), false);
15 | assertEquals(JSONValue.isValidJsonStrict(test), false);
16 | }
17 |
18 | public static void main(String[] args) {
19 | String test = "{'a':'b', 'c':'d'}";
20 | JSONObject obj = (JSONObject)JSONValue.parse(test);
21 | System.out.println(obj.toString(JSONStyle.NO_COMPRESS));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/Issue26.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONValue;
5 |
6 |
7 | public class Issue26 extends TestCase {
8 | public class AppInDb {
9 | protected int softid;
10 | protected transient String uuid;
11 | protected String softname;
12 | protected String infourl;
13 |
14 | public int getSoftid() {
15 | return softid;
16 | }
17 | public void setSoftid(int softid) {
18 | this.softid = softid;
19 | }
20 | public String getUuid() {
21 | return uuid;
22 | }
23 | public void setUuid(String uuid) {
24 | this.uuid = uuid;
25 | }
26 | public String getSoftname() {
27 | return softname;
28 | }
29 | public void setSoftname(String softname) {
30 | this.softname = softname;
31 | }
32 | public String getInfourl() {
33 | return infourl;
34 | }
35 | public void setInfourl(String infourl) {
36 | this.infourl = infourl;
37 | }
38 | }
39 |
40 | public class App extends AppInDb {
41 | public boolean isFree() {
42 | return free;
43 | }
44 | public void setFree(boolean free) {
45 | this.free = free;
46 | }
47 | public boolean isPlugin() {
48 | return plugin;
49 | }
50 | public void setPlugin(boolean plugin) {
51 | this.plugin = plugin;
52 | }
53 | protected boolean free;
54 | protected boolean plugin;
55 | }
56 |
57 | public void testIssue26() {
58 | App dbApp = new App();
59 | dbApp.setSoftname("sssssssssss");
60 | assertTrue(JSONValue.toJSONString(dbApp).contains("sssssssssss"));
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/JSONSimpleTest.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONArray;
5 | import net.minidev.json.parser.JSONParser;
6 |
7 | public class JSONSimpleTest extends TestCase {
8 | public void testLong() throws Exception {
9 | String s = "[1]";
10 | JSONParser p = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
11 | JSONArray array = (JSONArray) p.parse(s);
12 | assertEquals(Long.valueOf(1), (Long) array.get(0));
13 | }
14 |
15 | public void testDefault() throws Exception {
16 | String s = "[1]";
17 | JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE);
18 | JSONArray array = (JSONArray) p.parse(s);
19 | assertEquals(Integer.valueOf(1), (Integer) array.get(0));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/MustThrows.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.parser.JSONParser;
5 | import net.minidev.json.parser.ParseException;
6 |
7 | public class MustThrows {
8 |
9 | public static void testStrictInvalidJson(String json, int execptionType) throws Exception {
10 | testInvalidJson(json, JSONParser.MODE_RFC4627, execptionType);
11 | }
12 |
13 | public static void testInvalidJson(String json, int permissifMode, int execptionType) throws Exception {
14 | JSONParser p = new JSONParser(permissifMode);
15 | try {
16 | p.parse(json);
17 | TestCase.assertFalse("Exception Should Occure parsing:" + json, true);
18 | } catch (ParseException e) {
19 | if (execptionType == -1)
20 | execptionType = e.getErrorType();
21 | TestCase.assertEquals(execptionType, e.getErrorType());
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestBigValue.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import java.math.BigDecimal;
4 | import java.math.BigInteger;
5 | import java.util.HashMap;
6 |
7 | import org.junit.Test;
8 |
9 | import net.minidev.json.JSONObject;
10 | import net.minidev.json.JSONValue;
11 | import net.minidev.json.parser.JSONParser;
12 | import junit.framework.TestCase;
13 |
14 | public class TestBigValue extends TestCase {
15 | String bigStr = "12345678901234567890123456789";
16 |
17 | /**
18 | * test BigDecimal serialization
19 | */
20 | @Test
21 | public void testBigDecimal() {
22 | HashMap map = new HashMap();
23 | BigDecimal bigDec = new BigDecimal(bigStr + "." + bigStr);
24 | map.put("big", bigDec);
25 | String test = JSONValue.toJSONString(map);
26 | String result = "{\"big\":" + bigStr + "." +bigStr + "}";
27 | assertEquals(result, test);
28 | JSONObject obj = (JSONObject)JSONValue.parse(test);
29 | assertEquals(bigDec, obj.get("big"));
30 | assertEquals(bigDec.getClass(), obj.get("big").getClass());
31 | }
32 |
33 | /**
34 | * test BigInteger serialization
35 | */
36 | @Test
37 | public void testBigInteger() {
38 | HashMap map = new HashMap();
39 | BigInteger bigInt = new BigInteger(bigStr);
40 | map.put("big", bigInt);
41 | String test = JSONValue.toJSONString(map);
42 | String result = "{\"big\":" + bigStr + "}";
43 | assertEquals(result, test);
44 | JSONObject obj = (JSONObject)JSONValue.parse(test);
45 | assertEquals(bigInt, obj.get("big"));
46 | assertEquals(bigInt.getClass(), obj.get("big").getClass());
47 | }
48 | /**
49 | * https://github.com/netplex/json-smart-v1/issues/6
50 | */
51 | @Test
52 | public void testBigDouble() throws Exception {
53 | String content = "{\"customDouble\":3.14159265358979323846}";
54 | // System.out.printf("Input: %s\n", content);
55 | JSONParser parser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE);
56 | JSONObject jwtContent = (JSONObject) parser.parse(content);
57 | String serialized = jwtContent.toJSONString();
58 | // System.out.printf("Output: %s\n", serialized);
59 | assertEquals("should not loose precision", serialized, content);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestCompressor.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONStyleIdent;
5 | import net.minidev.json.JSONValue;
6 |
7 | public class TestCompressor extends TestCase {
8 | public static void main(String[] args) {
9 | JSONStyleIdent i = new JSONStyleIdent();
10 | String j = "{'a':{'b':'c','d':'e'},f:[1,2,'XYZ']}".replace('\'', '"');
11 | Object obj = JSONValue.parse(j);
12 | System.out.println(JSONValue.toJSONString(obj, i));
13 | }
14 |
15 | public void testCompressor() {
16 | String j = "{'a':{'b':'c','d':'e'},f:[1,2,'XYZ']}".replace('\'', '"');
17 | String sol = j.replace(" ", "").replace("\"", "");
18 | String comp = JSONValue.compress(j);
19 | assertEquals(sol, comp);
20 | }
21 |
22 | public void testCompressor2() {
23 | String j = "[{} ]";
24 | String sol = j.replace(" ", "");
25 | String comp = JSONValue.compress(j);
26 | assertEquals(sol, comp);
27 | }
28 |
29 | public void testCompressor3() {
30 | String j = "[[],[],[] ]";
31 | String sol = j.replace(" ", "");
32 | String comp = JSONValue.compress(j);
33 | assertEquals(sol, comp);
34 | }
35 |
36 | public void testCompressor4() {
37 | String j = "[[1],[2,3],[4] ]";
38 | String sol = j.replace(" ", "");
39 | String comp = JSONValue.compress(j);
40 | assertEquals(sol, comp);
41 | }
42 |
43 | public void testCompressor5() {
44 | String j = "[{},{},{} ]";
45 | String sol = j.replace(" ", "");
46 | String comp = JSONValue.compress(j);
47 | assertEquals(sol, comp);
48 | }
49 |
50 | public void testCompressor6() {
51 | String j = "[{a:b},{c:d},{e:f}]";
52 | String sol = j;
53 | String comp = JSONValue.compress(j);
54 | assertEquals(sol, comp);
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestCompressorFlags.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONObject;
5 | import net.minidev.json.JSONStyle;
6 | import net.minidev.json.JSONValue;
7 |
8 | /**
9 | * Test all Compression Styles
10 | *
11 | * @author Uriel Chemouni
12 | *
13 | */
14 | public class TestCompressorFlags extends TestCase {
15 |
16 | public void testProtect() throws Exception {
17 | String compressed = "{k:value}";
18 | String nCompress = "{\"k\":\"value\"}";
19 |
20 | JSONObject obj = (JSONObject) JSONValue.parse(nCompress);
21 |
22 | // test MAX_COMPRESS
23 | String r = obj.toJSONString(JSONStyle.MAX_COMPRESS);
24 | assertEquals(compressed, r);
25 |
26 | // test LT_COMPRESS
27 | r = obj.toJSONString(JSONStyle.LT_COMPRESS);
28 | assertEquals(nCompress, r);
29 |
30 | // test NO_COMPRESS
31 | r = obj.toJSONString(JSONStyle.NO_COMPRESS);
32 | assertEquals(nCompress, r);
33 |
34 | // only keys values
35 | JSONStyle style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_KEYS);
36 | r = obj.toJSONString(style);
37 | assertEquals("{k:\"value\"}", r);
38 |
39 | // only protect values
40 | style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_VALUES);
41 | r = obj.toJSONString(style);
42 | assertEquals("{\"k\":value}", r);
43 | }
44 |
45 | public void testAggresive() throws Exception {
46 | String r;
47 | JSONStyle style;
48 |
49 | String NProtectValue = "{\"a b\":\"c d\"}";
50 | JSONObject obj = (JSONObject) JSONValue.parse(NProtectValue);
51 |
52 | /**
53 | * Test Without Agressive
54 | */
55 | style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_KEYS);
56 | r = obj.toJSONString(style);
57 | assertEquals(NProtectValue, r);
58 |
59 | style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_VALUES);
60 | r = obj.toJSONString(style);
61 | assertEquals(NProtectValue, r);
62 |
63 | /**
64 | * Test With Agressive
65 | */
66 | style = new JSONStyle(-1 & (JSONStyle.FLAG_PROTECT_VALUES | JSONStyle.FLAG_AGRESSIVE));
67 | r = obj.toJSONString(style);
68 | assertEquals("{\"a b\":c d}", r);
69 |
70 | style = new JSONStyle(-1 & (JSONStyle.FLAG_PROTECT_KEYS | JSONStyle.FLAG_AGRESSIVE));
71 | r = obj.toJSONString(style);
72 | assertEquals("{a b:\"c d\"}", r);
73 |
74 | style = JSONStyle.MAX_COMPRESS;
75 | r = obj.toJSONString(style);
76 | assertEquals("{a b:c d}", r);
77 | }
78 |
79 | public void test4Web() throws Exception {
80 | String NProtectValue = "{\"k\":\"http:\\/\\/url\"}";
81 |
82 | JSONObject obj = (JSONObject) JSONValue.parse(NProtectValue);
83 |
84 | String r = obj.toJSONString(JSONStyle.MAX_COMPRESS);
85 | assertEquals("{k:\"http://url\"}", r);
86 |
87 | r = obj.toJSONString(JSONStyle.LT_COMPRESS);
88 | assertEquals("{\"k\":\"http://url\"}", r);
89 |
90 | r = obj.toJSONString(JSONStyle.NO_COMPRESS);
91 | assertEquals("{\"k\":\"http:\\/\\/url\"}", r);
92 | }
93 |
94 | }
95 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestFloat.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONObject;
5 | import net.minidev.json.JSONStyle;
6 | import net.minidev.json.parser.JSONParser;
7 |
8 | public class TestFloat extends TestCase {
9 | public static String[] TRUE_NUMBERS = new String[] { "1.0", "123.456", "1.0E1", "123.456E12", "1.0E+1",
10 | "123.456E+12", "1.0E-1", "123.456E-12", "1.0e1", "123.456e12", "1.0e+1", "123.456e+12", "1.0e-1",
11 | "123.456e-12" };
12 |
13 | public static String[] FALSE_NUMBERS = new String[] { "1.0%", "123.45.6", "1.0E", "++123.456E12", "+-01",
14 | "1.0E+1.2" };
15 |
16 | public void testFloat() throws Exception {
17 | JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE);
18 | for (String s : TRUE_NUMBERS) {
19 | String json = "{v:" + s + "}";
20 | Double val = Double.valueOf(s.trim());
21 | JSONObject obj = (JSONObject) p.parse(json);
22 | Object value = obj.get("v");
23 | assertEquals("Should be parse as double", val, value);
24 | }
25 | }
26 |
27 | public void testNonFloat() throws Exception {
28 | JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE);
29 | for (String s : FALSE_NUMBERS) {
30 | String json = "{v:" + s + "}";
31 | JSONObject obj = (JSONObject) p.parse(json);
32 | assertEquals("Should be parse as string", s, obj.get("v"));
33 |
34 | String correct = "{\"v\":\"" + s + "\"}";
35 | assertEquals("Should be re serialized as", correct, obj.toJSONString());
36 | }
37 | }
38 |
39 | /**
40 | * Error reported in issue 44
41 | */
42 | public void testUUID() {
43 | String UUID = "58860611416142319131902418361e88";
44 | JSONObject obj = new JSONObject();
45 | obj.put("uuid", UUID);
46 | String compressed = obj.toJSONString(JSONStyle.MAX_COMPRESS);
47 | assertTrue(compressed.contains("uuid:\""));
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestFloatStrict.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONObject;
5 | import net.minidev.json.parser.JSONParser;
6 |
7 | public class TestFloatStrict extends TestCase {
8 |
9 | public void testFloat() throws Exception {
10 | for (String s : TestFloat.TRUE_NUMBERS) {
11 | String json = "{\"v\":" + s + "}";
12 | Double val = Double.valueOf(s.trim());
13 | JSONObject obj = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(json);
14 | Object value = obj.get("v");
15 | assertEquals("Should be parse as double", val, value);
16 | }
17 | }
18 |
19 | public void testNonFloat() throws Exception {
20 | for (String s : TestFloat.FALSE_NUMBERS) {
21 | String json = "{\"v\":" + s + "}";
22 | MustThrows.testStrictInvalidJson(json, -1);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestInts.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import java.math.BigDecimal;
4 | import java.math.BigInteger;
5 |
6 | import junit.framework.TestCase;
7 | import net.minidev.json.JSONObject;
8 | import net.minidev.json.parser.JSONParser;
9 | import net.minidev.json.parser.ParseException;
10 |
11 | public class TestInts extends TestCase {
12 |
13 | public void testIntMax() throws Exception {
14 | String s = "{t:" + Integer.MAX_VALUE + "}";
15 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
16 | assertEquals(o.get("t"), Integer.MAX_VALUE);
17 | }
18 |
19 | public void testIntMin() throws Exception {
20 | String s = "{t:" + Integer.MIN_VALUE + "}";
21 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
22 | assertEquals(o.get("t"), Integer.MIN_VALUE);
23 | }
24 |
25 | public void testIntResult() throws Exception {
26 | String s = "{\"t\":1}";
27 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s);
28 | assertEquals(o.get("t"), Integer.valueOf(1));
29 |
30 | o = (JSONObject) new JSONParser(JSONParser.MODE_JSON_SIMPLE).parse(s);
31 | assertEquals(o.get("t"), Long.valueOf(1));
32 |
33 | o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
34 | assertEquals(o.get("t"), Integer.valueOf(1));
35 | }
36 |
37 | public void testInt() throws Exception {
38 | String s = "{t:90}";
39 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
40 | assertEquals(o.get("t"), Integer.valueOf(90));
41 | }
42 |
43 | public void testIntNeg() throws Exception {
44 | String s = "{t:-90}";
45 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
46 | assertEquals(o.get("t"), -90);
47 | }
48 |
49 | public void testBigInt() throws Exception {
50 | StringBuilder sb = new StringBuilder();
51 | for (int i = 0; i < 10; i++)
52 | sb.append(Integer.MAX_VALUE);
53 | String bigText = sb.toString();
54 | BigInteger big = new BigInteger(bigText, 10);
55 | String s = "{t:" + bigText + "}";
56 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
57 | assertEquals(o.get("t"), big);
58 | }
59 |
60 | public void testBigDoubleInt() throws Exception {
61 | StringBuilder sb = new StringBuilder();
62 | for (int i = 0; i < 10; i++)
63 | sb.append(Integer.MAX_VALUE);
64 | sb.append('.');
65 | for (int i = 0; i < 10; i++)
66 | sb.append(Integer.MAX_VALUE);
67 |
68 | String bigText = sb.toString();
69 | BigDecimal big = new BigDecimal(bigText);
70 | String s = "{\"t\":" + bigText + "}";
71 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s);
72 | assertEquals(o.get("t"), big);
73 | o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
74 | assertEquals(o.get("t"), big);
75 | }
76 |
77 | public void testjunkTaillingData() throws Exception {
78 | String s = "{\"t\":124}$ifsisg045";
79 |
80 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_JSON_SIMPLE).parse(s);
81 | assertEquals(o.get("t"), 124L);
82 |
83 | MustThrows.testInvalidJson(s, JSONParser.MODE_RFC4627, ParseException.ERROR_UNEXPECTED_TOKEN);
84 | // o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s);
85 | // assertEquals(o.get("t"), 124);
86 |
87 | o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
88 | assertEquals(o.get("t"), 124);
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestInvalidNumber.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONObject;
5 | import net.minidev.json.JSONStyle;
6 | import net.minidev.json.JSONValue;
7 |
8 | public class TestInvalidNumber extends TestCase {
9 |
10 | public void testF1() {
11 | String test = "51e88";
12 | JSONObject o = new JSONObject();
13 | o.put("a", test);
14 | String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS);
15 | assertEquals("{a:\"51e88\"}", comp);
16 |
17 | o = (JSONObject)JSONValue.parse(comp);
18 | assertEquals(o.get("a"), test);
19 | }
20 |
21 | public void testF2() {
22 | String test = "51e+88";
23 | JSONObject o = new JSONObject();
24 | o.put("a", test);
25 | String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS);
26 | assertEquals("{a:\"51e+88\"}", comp);
27 |
28 | o = (JSONObject)JSONValue.parse(comp);
29 | assertEquals(o.get("a"), test);
30 | }
31 |
32 | public void testF3() {
33 | String test = "51e-88";
34 | JSONObject o = new JSONObject();
35 | o.put("a", test);
36 | String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS);
37 | assertEquals("{a:\"51e-88\"}", comp);
38 |
39 | o = (JSONObject)JSONValue.parse(comp);
40 | assertEquals(o.get("a"), test);
41 | }
42 |
43 | public void testF4() {
44 | String test = "51ee88";
45 | JSONObject o = new JSONObject();
46 | o.put("a", test);
47 | String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS);
48 | assertEquals("{a:51ee88}", comp);
49 |
50 | o = (JSONObject)JSONValue.parse(comp);
51 | assertEquals(o.get("a"), test);
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestKeyword.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONObject;
5 | import net.minidev.json.parser.JSONParser;
6 | import net.minidev.json.parser.ParseException;
7 |
8 | public class TestKeyword extends TestCase {
9 |
10 | public void testBool() throws Exception {
11 | String s = "{t:true}";
12 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
13 | assertEquals(o.get("t"), true);
14 |
15 | s = "{t:false}";
16 | o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
17 | assertEquals(o.get("t"), false);
18 | }
19 |
20 | public void testNull() throws Exception {
21 | String s = "{t:null}";
22 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
23 | assertNull(o.get("t"));
24 | }
25 |
26 | public void testNaN() throws Exception {
27 | String s = "{t:NaN}";
28 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
29 | assertEquals(o.get("t"), Float.NaN);
30 | }
31 |
32 | public void testNaNStrict() throws Exception {
33 | String s = "{\"t\":NaN}";
34 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_TOKEN);
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestMisc.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONArray;
5 | import net.minidev.json.JSONObject;
6 | import net.minidev.json.JSONValue;
7 |
8 | public class TestMisc extends TestCase {
9 |
10 | public void testIssue23() throws Exception {
11 | String s = JSONValue.toJSONString(new int[] { 1, 2, 50, 1234, 10000 });
12 | assertEquals("[1,2,50,1234,10000]", s);
13 | }
14 |
15 | public void testEmptyStrict() throws Exception {
16 | String s = "{\"key1\":\"v1\", \"key2\":{}, \"key3\":[]}";
17 | JSONObject o = (JSONObject) JSONValue.parseStrict(s);
18 |
19 | assertEquals(o.get("key1"), "v1");
20 | assertEquals(((JSONObject) o.get("key2")).size(), 0);
21 | assertEquals(((JSONArray) o.get("key3")).size(), 0);
22 | }
23 |
24 | public void testBool() throws Exception {
25 | String s = "{\"key1\":\"v1\", \"key2\":{}, \"key3\":[]}";
26 | JSONObject o = (JSONObject) JSONValue.parseWithException(s);
27 |
28 | assertEquals(o.get("key1"), "v1");
29 | assertEquals(((JSONObject) o.get("key2")).size(), 0);
30 | assertEquals(((JSONArray) o.get("key3")).size(), 0);
31 | }
32 |
33 | public void testInt() throws Exception {
34 | String s = "123";
35 | Object o = JSONValue.parseWithException(s);
36 | assertEquals(o, 123);
37 | }
38 |
39 | public void testIntOffset() throws Exception {
40 | String s = "AA 123";
41 | Object o = JSONValue.parseWithException(s.getBytes(), 3, s.length());
42 | assertEquals(o, 123);
43 | }
44 |
45 | public void testFloat() throws Exception {
46 | String s = "123.5";
47 | Object o = JSONValue.parseWithException(s);
48 | assertEquals(o, Double.valueOf(123.5));
49 | }
50 |
51 | public void testFloat2() throws Exception {
52 | String s = "123.5E1";
53 | Object o = JSONValue.parseWithException(s);
54 | assertEquals(o, Double.valueOf(1235));
55 | }
56 |
57 | public void testFloat3() throws Exception {
58 | String s = "123..5";
59 | Object o = JSONValue.parseWithException(s);
60 | assertEquals(o, "123..5");
61 | }
62 |
63 | public void testFloat4() throws Exception {
64 | String s = "123é.5";
65 | Object o = JSONValue.parseWithException(s);
66 | assertEquals(o, 123);
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestNavi.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import java.util.Collection;
4 |
5 | import junit.framework.TestCase;
6 | import net.minidev.json.JSONNavi;
7 | import net.minidev.json.JSONObject;
8 |
9 | public class TestNavi extends TestCase {
10 | public void testNaviWrite() {
11 | JSONNavi> nav = JSONNavi.newInstanceOrdered();
12 | nav.set("name", "jhone").set("age", 42).at("childName").add("fifi", "riri", "loulou").up().at("cat")
13 | .set("color", "red");
14 | String s1 = "{\"name\":\"jhone\",\"age\":42,\"childName\":[\"fifi\",\"riri\",\"loulou\"],\"cat\":{\"color\":\"red\"}}";
15 | assertEquals(s1, nav.toString());
16 | }
17 |
18 | public void testNaviWrite2() {
19 | // ContainerFactory.FACTORY_ORDERED JSONNavi should keep order
20 | JSONNavi> nav = JSONNavi.newInstanceOrdered();
21 | nav.at("name").set("toto").up().set("tutu", "V2").at("size").set("width", 10).set("higth", 35).up(3)
22 | .set("FinUp", 1).at("array").add(0, 1, 2, 3, 4, 5);
23 | nav.at(-1);
24 | assertEquals("/array[5]", nav.getJPath());
25 | String s1 = "{'name':'toto','tutu':'V2','size':{'width':10,'higth':35},'FinUp':1,'array':[0,1,2,3,4,5]}"
26 | .replace('\'', '"');
27 | assertEquals(s1, nav.toString());
28 | }
29 |
30 | public void testNaviRead() {
31 | String json = "{name:foo,str:null,ar:[1,2,3,4]}";
32 |
33 | JSONNavi nav = new JSONNavi(json);
34 | nav.at(5);
35 | assertTrue("Navigator should be in error stat", nav.hasFailure());
36 | nav.root();
37 | assertEquals(3, nav.at("ar").at(2).asInt());
38 | nav.up(2);
39 | assertEquals(4, nav.at("ar").at(-1).asInt());
40 | nav.up(2);
41 | assertEquals("foo", nav.at("name").asString());
42 | }
43 |
44 | public void testNaviWriteArray() {
45 | String expected = "{'type':'bundle','data':[{'type':'object','name':'obj1'},{'type':'object','name':'obj2'}]}"
46 | .replace('\'', '"');
47 | JSONNavi> nav = JSONNavi.newInstanceOrdered();
48 | nav.set("type", "bundle").at("data").array().at(0).set("type", "object").set("name", "obj1").up().at(1)
49 | .set("type", "object").set("name", "obj2").root();
50 | assertEquals(expected, nav.toString());
51 |
52 | nav = JSONNavi.newInstanceOrdered();
53 | nav.set("type", "bundle").at("data").array().atNext().set("type", "object").set("name", "obj1").up().atNext()
54 | .set("type", "object").set("name", "obj2").root();
55 | assertEquals(expected, nav.toString());
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestNumberPrecision.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import java.math.BigInteger;
4 |
5 | import junit.framework.TestCase;
6 | import net.minidev.json.JSONArray;
7 | import net.minidev.json.JSONValue;
8 |
9 | public class TestNumberPrecision extends TestCase {
10 | public void testMaxLong() {
11 | Long v = Long.MAX_VALUE;
12 | String s = "[" + v + "]";
13 | JSONArray array = (JSONArray) JSONValue.parse(s);
14 | Object r = array.get(0);
15 | assertEquals(v, r);
16 | }
17 |
18 | public void testMinLong() {
19 | Long v = Long.MIN_VALUE;
20 | String s = "[" + v + "]";
21 | JSONArray array = (JSONArray) JSONValue.parse(s);
22 | Object r = array.get(0);
23 | assertEquals(v, r);
24 | }
25 |
26 | public void testMinBig() {
27 | BigInteger v = BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE);
28 | String s = "[" + v + "]";
29 | JSONArray array = (JSONArray) JSONValue.parse(s);
30 | Object r = array.get(0);
31 | assertEquals(v, r);
32 | }
33 |
34 | public void testMaxBig() {
35 | BigInteger v = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE);
36 | String s = "[" + v + "]";
37 | JSONArray array = (JSONArray) JSONValue.parse(s);
38 | Object r = array.get(0);
39 | assertEquals(v, r);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestStrict.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONObject;
5 | import net.minidev.json.parser.JSONParser;
6 | import net.minidev.json.parser.ParseException;
7 |
8 | public class TestStrict extends TestCase {
9 |
10 | public void testS1() throws Exception {
11 | String text = "My Test";
12 | String s = "{t:\"" + text + "\"}";
13 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
14 | assertEquals(o.get("t"), text);
15 | }
16 |
17 | public void testS2() throws Exception {
18 | String text = "My Test";
19 | String s = "{t:'" + text + "'}";
20 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
21 | assertEquals(o.get("t"), text);
22 | }
23 |
24 | public void testSEscape() throws Exception {
25 | String text = "My\r\nTest";
26 | String text2 = "My\\r\\nTest";
27 | String s = "{t:'" + text2 + "'}";
28 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
29 | assertEquals(o.get("t"), text);
30 | }
31 |
32 | public void testBadString() throws Exception {
33 | String s = "{\"t\":\"Before\u000CAfter\"}";
34 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
35 | assertEquals("Before\u000CAfter", o.get("t"));
36 | try {
37 | o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s);
38 | assertEquals("nothink", o.get("t"));
39 | } catch (ParseException e) {
40 | assertEquals("Exception", "Exception");
41 | }
42 | }
43 | /**
44 | * issue report gitHub 8 by jochenberger
45 | */
46 | public void testDataAfterValue() throws Exception {
47 | String s = "{\"foo\":\"bar\"x}";
48 | MustThrows.testInvalidJson(s, JSONParser.MODE_STRICTEST | JSONParser.ACCEPT_TAILLING_SPACE, ParseException.ERROR_UNEXPECTED_TOKEN);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestString.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONObject;
5 | import net.minidev.json.parser.JSONParser;
6 | import net.minidev.json.parser.ParseException;
7 |
8 | public class TestString extends TestCase {
9 |
10 | public void testS0() throws Exception {
11 | MustThrows.testStrictInvalidJson("{\"1\":\"one\"\n\"2\":\"two\"}", ParseException.ERROR_UNEXPECTED_TOKEN);
12 | }
13 |
14 | public void testS1() throws Exception {
15 | String text = "My Test";
16 | String s = "{t:\"" + text + "\"}";
17 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
18 | assertEquals(o.get("t"), text);
19 | }
20 |
21 | public void testS2() throws Exception {
22 | String text = "My Test";
23 | String s = "{t:'" + text + "'}";
24 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
25 | assertEquals(o.get("t"), text);
26 | }
27 |
28 | public void testSEscape() throws Exception {
29 | String text = "My\r\nTest";
30 | String text2 = "My\\r\\nTest";
31 | String s = "{t:'" + text2 + "'}";
32 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
33 | assertEquals(o.get("t"), text);
34 | }
35 |
36 | public void testBadString() throws Exception {
37 | String s = "{\"t\":\"Before\u000CAfter\"}";
38 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
39 | assertEquals("Before\u000CAfter", o.get("t"));
40 | try {
41 | o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s);
42 | assertEquals("nothink", o.get("t"));
43 | } catch (ParseException e) {
44 | assertEquals("Exception", "Exception");
45 | }
46 | }
47 |
48 | public void testXescape() throws Exception {
49 | String s = "{\"t\":\"\\x41\\x42\\x43\"}";
50 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
51 | assertEquals("ABC", o.get("t"));
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestStringStrict.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import net.minidev.json.parser.ParseException;
4 | import junit.framework.TestCase;
5 |
6 | public class TestStringStrict extends TestCase {
7 |
8 | public void testS1() throws Exception {
9 | String text = "My Test";
10 | String s = "{t:\"" + text + "\"}";
11 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_TOKEN);
12 | }
13 | public void testSEscape() throws Exception {
14 | String text2 = "My\\r\\nTest";
15 | String s = "{\"t\":'" + text2 + "'}";
16 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestTruncated.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import net.minidev.json.parser.ParseException;
4 | import junit.framework.TestCase;
5 |
6 | public class TestTruncated extends TestCase {
7 |
8 | public void testS1() throws Exception {
9 | String s = "{\"key\":{}";
10 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_EOF);
11 | }
12 |
13 | public void testS2() throws Exception {
14 | String s = "{\"key\":";
15 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_EOF);
16 | }
17 |
18 | public void testS3() throws Exception {
19 | String s = "{\"key\":123";
20 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_EOF);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/TestUtf8.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test;
2 |
3 | import java.io.ByteArrayInputStream;
4 | import java.io.StringReader;
5 |
6 | import junit.framework.TestCase;
7 | import net.minidev.json.JSONObject;
8 | import net.minidev.json.JSONValue;
9 |
10 | public class TestUtf8 extends TestCase {
11 | // Sinhalese language
12 | static String[] nonLatinTexts = new String[] { "සිංහල ජාතිය", "日本語", "Русский", "فارسی", "한국어", "Հայերեն", "हिन्दी", "עברית", "中文", "አማርኛ", "മലയാളം",
13 | "ܐܬܘܪܝܐ", "მარგალური" };
14 |
15 | public void testString() throws Exception {
16 | for (String nonLatinText : nonLatinTexts) {
17 | String s = "{\"key\":\"" + nonLatinText + "\"}";
18 | JSONObject obj = (JSONObject) JSONValue.parse(s);
19 | String v = (String) obj.get("key"); // result is incorrect
20 | // System.out.println(v);
21 | assertEquals(v, nonLatinText);
22 | }
23 | }
24 |
25 | public void testReader() throws Exception {
26 | for (String nonLatinText : nonLatinTexts) {
27 | String s = "{\"key\":\"" + nonLatinText + "\"}";
28 | StringReader reader = new StringReader(s);
29 | JSONObject obj = (JSONObject) JSONValue.parse(reader);
30 |
31 | String v = (String) obj.get("key"); // result is incorrect
32 | // System.out.println(v);
33 | assertEquals(v, nonLatinText);
34 | }
35 | }
36 |
37 | public void testInputStream() throws Exception {
38 | for (String nonLatinText : nonLatinTexts) {
39 | String s = "{\"key\":\"" + nonLatinText + "\"}";
40 | ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes("utf8"));
41 | JSONObject obj = (JSONObject) JSONValue.parse(bis);
42 | String v = (String) obj.get("key"); // result is incorrect
43 | // System.out.println(v);
44 | assertEquals(v, nonLatinText);
45 | }
46 | }
47 |
48 | public void testBytes() throws Exception {
49 | for (String nonLatinText : nonLatinTexts) {
50 | String s = "{\"key\":\"" + nonLatinText + "\"}";
51 | byte[] bs = s.getBytes("utf8");
52 | JSONObject obj = (JSONObject) JSONValue.parse(bs);
53 | String v = (String) obj.get("key"); // result is incorrect
54 | // System.out.println(v);
55 | assertEquals(v, nonLatinText);
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/strict/TestExcessiveComma.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test.strict;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONValue;
5 | import net.minidev.json.parser.ParseException;
6 | import net.minidev.json.test.MustThrows;
7 |
8 | public class TestExcessiveComma extends TestCase {
9 | public void testExcessiveComma1A() throws Exception {
10 | String s = "[1,2,,3]";
11 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR);
12 | JSONValue.parseWithException(s);
13 | }
14 |
15 | public void testExcessiveComma2A() throws Exception {
16 | String s = "[1,2,]";
17 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR);
18 | JSONValue.parseWithException(s);
19 | }
20 |
21 | public void testExcessiveComma3A() throws Exception {
22 | String s = "[,]";
23 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR);
24 | JSONValue.parseWithException(s);
25 | }
26 |
27 | public void testExcessiveComma1O() throws Exception {
28 | String s = "{\"a\":1,,\"b\":1}";
29 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR);
30 | JSONValue.parseWithException(s);
31 | }
32 |
33 | public void testExcessiveComma2O() throws Exception {
34 | String s = "{\"a\":1,}";
35 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR);
36 | JSONValue.parseWithException(s);
37 | }
38 |
39 | public void testExcessiveComma3O() throws Exception {
40 | String s = "{,}";
41 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_CHAR);
42 | JSONValue.parseWithException(s);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/strict/TestTaillingJunk.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test.strict;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONObject;
5 | import net.minidev.json.parser.JSONParser;
6 | import net.minidev.json.parser.ParseException;
7 | import net.minidev.json.test.MustThrows;
8 |
9 | /**
10 | * @since 1.0.7
11 | */
12 | public class TestTaillingJunk extends TestCase {
13 |
14 | public void testTaillingSpace() throws Exception {
15 | String s = "{\"t\":0} ";
16 | MustThrows.testInvalidJson(s, JSONParser.MODE_STRICTEST, ParseException.ERROR_UNEXPECTED_TOKEN);
17 |
18 | s = "{\"t\":0} ";
19 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_STRICTEST | JSONParser.ACCEPT_TAILLING_SPACE).parse(s);
20 | assertEquals(o.get("t"), 0);
21 | }
22 |
23 | public void testTaillingSpace2() throws Exception {
24 | String s = "{\"t\":0} \r\n ";
25 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_STRICTEST | JSONParser.ACCEPT_TAILLING_SPACE).parse(s);
26 | assertEquals(o.get("t"), 0);
27 | }
28 |
29 | public void testTaillingData() throws Exception {
30 | String s = "{\"t\":0} 0";
31 | MustThrows.testInvalidJson(s, JSONParser.MODE_STRICTEST, ParseException.ERROR_UNEXPECTED_TOKEN);
32 | }
33 |
34 | public void testTaillingDataPermisive() throws Exception {
35 | String s = "{\"t\":0} 0";
36 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
37 | assertEquals(o.get("t"), 0);
38 | }
39 |
40 | public void testTaillingDataWithSpaceAllowed() throws Exception {
41 | String s = "{\"t\":0}{";
42 | MustThrows.testInvalidJson(s, JSONParser.MODE_STRICTEST | JSONParser.ACCEPT_TAILLING_SPACE, ParseException.ERROR_UNEXPECTED_TOKEN);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/strict/TestZeroLead.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test.strict;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONArray;
5 | import net.minidev.json.JSONObject;
6 | import net.minidev.json.JSONValue;
7 | import net.minidev.json.parser.JSONParser;
8 | import net.minidev.json.parser.ParseException;
9 | import net.minidev.json.test.MustThrows;
10 |
11 | /**
12 | * @since 1.0.7
13 | */
14 | public class TestZeroLead extends TestCase {
15 |
16 | public void test0O() throws Exception {
17 | String s = "{\"t\":0}";
18 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_RFC4627).parse(s);
19 | assertEquals(o.get("t"), 0);
20 | JSONValue.parseWithException(s);
21 | }
22 |
23 | public void test0A() throws Exception {
24 | String s = "[0]";
25 | JSONArray o = (JSONArray) new JSONParser(JSONParser.MODE_RFC4627).parse(s);
26 | assertEquals(o.get(0), 0);
27 | JSONValue.parseWithException(s);
28 | }
29 |
30 | public void test0Float() throws Exception {
31 | String s = "[00.0]";
32 | // strict
33 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_LEADING_0);
34 | // PERMISIVE
35 | JSONValue.parseWithException(s);
36 | }
37 |
38 | public void test01Float() throws Exception {
39 | String s = "[01.0]";
40 | // strict
41 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_LEADING_0);
42 | // PERMISIVE
43 | JSONValue.parseWithException(s);
44 | }
45 |
46 | public void test00001() throws Exception {
47 | String s = "{\"t\":00001}";
48 | JSONObject o = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
49 | assertEquals(o.get("t"), 1);
50 | JSONValue.parseWithException(s);
51 | }
52 |
53 | public void test00001Strict() throws Exception {
54 | String s = "{\"t\":00001}";
55 | MustThrows.testStrictInvalidJson(s, ParseException.ERROR_UNEXPECTED_LEADING_0);
56 | JSONValue.parseWithException(s);
57 | }
58 |
59 | public void testDup() throws Exception {
60 | String s = "{'t':1,'t':2}";
61 | try {
62 | new JSONParser(JSONParser.MODE_PERMISSIVE).parse(s);
63 | assertEquals("Should Stack", "");
64 | } catch (ParseException e) {
65 | assertEquals(ParseException.ERROR_UNEXPECTED_DUPLICATE_KEY, e.getErrorType());
66 | }
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/test/writer/TestWriteFeatures.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.test.writer;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONStyle;
5 | import net.minidev.json.JSONValue;
6 |
7 | public class TestWriteFeatures extends TestCase {
8 |
9 | public void testS1() throws Exception {
10 | Beans beans = new Beans();
11 | String s = JSONValue.toJSONString(beans, JSONStyle.MAX_COMPRESS);
12 | assertEquals("{}", s);
13 | s = JSONValue.toJSONString(beans, JSONStyle.NO_COMPRESS);
14 | if (s.startsWith("{\"b")) {
15 | assertEquals("{\"b\":null,\"a\":null}", s);
16 | } else {
17 | assertEquals("{\"a\":null,\"b\":null}", s);
18 | }
19 | beans.a = "a";
20 | s = JSONValue.toJSONString(beans, JSONStyle.MAX_COMPRESS);
21 | assertEquals("{a:a}", s);
22 | }
23 |
24 | public static class Beans {
25 | public String a;
26 | public String b;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/testMapping/TestMapBeans.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.testMapping;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | import junit.framework.TestCase;
7 | import net.minidev.json.JSONValue;
8 |
9 | public class TestMapBeans extends TestCase {
10 |
11 | public void testSerObjInts() throws Exception {
12 | String s = "{\"vint\":[1,2,3]}";
13 | T1 r = new T1();
14 | r.vint = new int[] { 1, 2, 3 };
15 | String s2 = JSONValue.toJSONString(r);
16 | assertEquals(s, s2);
17 | }
18 |
19 | public void testSerObjIntKey() throws Exception {
20 | String s = "{\"data\":{\"1\":\"toto\"}}";
21 | T2 r = new T2();
22 | r.data = new HashMap();
23 | r.data.put(1, "toto");
24 | String s2 = JSONValue.toJSONString(r);
25 | assertEquals(s, s2);
26 | }
27 |
28 | public void testSerObjEnumKey() throws Exception {
29 | String s = "{\"data\":{\"red\":10}}";
30 | T3 r = new T3();
31 | r.data = new HashMap();
32 | r.data.put(ColorEnum.red, 10);
33 | String s2 = JSONValue.toJSONString(r);
34 | assertEquals(s, s2);
35 | }
36 |
37 | public void testSerObjBool1() throws Exception {
38 | String s = "{\"data\":true}";
39 | T4 r = new T4();
40 | r.data = true;
41 | String s2 = JSONValue.toJSONString(r);
42 | assertEquals(s, s2);
43 | }
44 |
45 | public void testSerObjBool2() throws Exception {
46 | String s = "{\"data\":true}";
47 | T5 r = new T5();
48 | r.data = true;
49 | String s2 = JSONValue.toJSONString(r);
50 | assertEquals(s, s2);
51 | }
52 |
53 | public static class T1 {
54 | private int[] vint;
55 |
56 | public int[] getVint() {
57 | return vint;
58 | }
59 |
60 | public void setVint(int[] vint) {
61 | this.vint = vint;
62 | }
63 | }
64 |
65 | public static class T2 {
66 | private Map data;
67 |
68 | public Map getData() {
69 | return data;
70 | }
71 |
72 | public void setData(Map data) {
73 | this.data = data;
74 | }
75 | }
76 |
77 | public static enum ColorEnum {
78 | bleu, green, red, yellow
79 | }
80 |
81 | public static class T3 {
82 | private Map data;
83 |
84 | public Map getData() {
85 | return data;
86 | }
87 |
88 | public void setData(Map data) {
89 | this.data = data;
90 | }
91 | }
92 |
93 | public static class T4 {
94 | private boolean data;
95 |
96 | public boolean getData() {
97 | return data;
98 | }
99 |
100 | public void setData(boolean data) {
101 | this.data = data;
102 | }
103 | }
104 |
105 | public static class T5 {
106 | private boolean data;
107 |
108 | public boolean isData() {
109 | return data;
110 | }
111 |
112 | public void setData(boolean data) {
113 | this.data = data;
114 | }
115 | }
116 |
117 | }
118 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/testMapping/TestMapPublic.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.testMapping;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONValue;
5 |
6 | public class TestMapPublic extends TestCase {
7 | String MuliTyepJson = "{\"name\":\"B\",\"age\":120,\"cost\":12000,\"flag\":3,\"valid\":true,\"f\":1.2,\"d\":1.5,\"l\":12345678912345}";
8 |
9 | public void testSerObjMixte() throws Exception {
10 | T2 r = new T2();
11 | r.name = "B";
12 | r.age = 120;
13 | r.cost = 12000;
14 | r.flag = 3;
15 | r.valid = true;
16 | r.name = "B";
17 | r.f = 1.2F;
18 | r.d = 1.5;
19 | r.l = 12345678912345L;
20 | String s = JSONValue.toJSONString(r);
21 |
22 | assertEquals(MuliTyepJson, s);
23 | }
24 |
25 | public void testSerObjMixtePrim() throws Exception {
26 | T3 r = new T3();
27 | r.name = "B";
28 | r.age = 120;
29 | r.cost = 12000;
30 | r.flag = 3;
31 | r.valid = true;
32 | r.name = "B";
33 | r.f = 1.2F;
34 | r.d = 1.5;
35 | r.l = 12345678912345L;
36 | String s = JSONValue.toJSONString(r);
37 | assertEquals(MuliTyepJson, s);
38 | }
39 |
40 | public void testSerObjMixteAcc() throws Exception {
41 | T4 r = new T4();
42 | r.name = "B";
43 | r.age = 120;
44 | r.cost = 12000;
45 | r.flag = 3;
46 | r.valid = true;
47 | r.name = "B";
48 | r.f = 1.2F;
49 | r.d = 1.5;
50 | r.l = 12345678912345L;
51 | String s = JSONValue.toJSONString(r);
52 | assertEquals(MuliTyepJson, s);
53 | }
54 |
55 | public void testSerObjMixtePrimAcc() throws Exception {
56 | T5 r = new T5();
57 | r.name = "B";
58 | r.age = 120;
59 | r.cost = 12000;
60 | r.flag = 3;
61 | r.valid = true;
62 | r.name = "B";
63 | r.f = 1.2F;
64 | r.d = 1.5;
65 | r.l = 12345678912345L;
66 | String s = JSONValue.toJSONString(r);
67 | assertEquals(MuliTyepJson, s);
68 | }
69 |
70 | public static class T2 {
71 | public String name;
72 | public short age;
73 | public int cost;
74 | public byte flag;
75 | public boolean valid;
76 | public float f;
77 | public double d;
78 | public long l;
79 | }
80 |
81 | public static class T3 {
82 | public String name;
83 | public Short age;
84 | public Integer cost;
85 | public Byte flag;
86 | public Boolean valid;
87 | public Float f;
88 | public Double d;
89 | public Long l;
90 | }
91 |
92 | public static class T4 {
93 | private String name;
94 | private short age;
95 | private int cost;
96 | private byte flag;
97 | private boolean valid;
98 | private float f;
99 | private double d;
100 | private long l;
101 |
102 | public String getName() {
103 | return name;
104 | }
105 |
106 | public void setName(String name) {
107 | this.name = name;
108 | }
109 |
110 | public short getAge() {
111 | return age;
112 | }
113 |
114 | public void setAge(short age) {
115 | this.age = age;
116 | }
117 |
118 | public int getCost() {
119 | return cost;
120 | }
121 |
122 | public void setCost(int cost) {
123 | this.cost = cost;
124 | }
125 |
126 | public byte getFlag() {
127 | return flag;
128 | }
129 |
130 | public void setFlag(byte flag) {
131 | this.flag = flag;
132 | }
133 |
134 | public boolean isValid() {
135 | return valid;
136 | }
137 |
138 | public void setValid(boolean valid) {
139 | this.valid = valid;
140 | }
141 |
142 | public float getF() {
143 | return f;
144 | }
145 |
146 | public void setF(float f) {
147 | this.f = f;
148 | }
149 |
150 | public double getD() {
151 | return d;
152 | }
153 |
154 | public void setD(double d) {
155 | this.d = d;
156 | }
157 |
158 | public long getL() {
159 | return l;
160 | }
161 |
162 | public void setL(long l) {
163 | this.l = l;
164 | }
165 | }
166 |
167 | public static class T5 {
168 | private String name;
169 | private Short age;
170 | private Integer cost;
171 | private Byte flag;
172 | private Boolean valid;
173 | private Float f;
174 | private Double d;
175 | private Long l;
176 |
177 | public String getName() {
178 | return name;
179 | }
180 |
181 | public void setName(String name) {
182 | this.name = name;
183 | }
184 |
185 | public Short getAge() {
186 | return age;
187 | }
188 |
189 | public void setAge(Short age) {
190 | this.age = age;
191 | }
192 |
193 | public Integer getCost() {
194 | return cost;
195 | }
196 |
197 | public void setCost(Integer cost) {
198 | this.cost = cost;
199 | }
200 |
201 | public Byte getFlag() {
202 | return flag;
203 | }
204 |
205 | public void setFlag(Byte flag) {
206 | this.flag = flag;
207 | }
208 |
209 | public Boolean getValid() {
210 | return valid;
211 | }
212 |
213 | public void setValid(Boolean valid) {
214 | this.valid = valid;
215 | }
216 |
217 | public Float getF() {
218 | return f;
219 | }
220 |
221 | public void setF(Float f) {
222 | this.f = f;
223 | }
224 |
225 | public Double getD() {
226 | return d;
227 | }
228 |
229 | public void setD(Double d) {
230 | this.d = d;
231 | }
232 |
233 | public Long getL() {
234 | return l;
235 | }
236 |
237 | public void setL(Long l) {
238 | this.l = l;
239 | }
240 | }
241 |
242 | }
243 |
--------------------------------------------------------------------------------
/json-smart/src/test/java/net/minidev/json/testMapping/TestSerPrimArrays.java:
--------------------------------------------------------------------------------
1 | package net.minidev.json.testMapping;
2 |
3 | import junit.framework.TestCase;
4 | import net.minidev.json.JSONValue;
5 |
6 | public class TestSerPrimArrays extends TestCase {
7 | public void testBooleans() throws Exception {
8 | String s = "[true,true,false]";
9 | boolean[] bs = new boolean[] { true, true, false };
10 | String s2 = JSONValue.toJSONString(bs);
11 | assertEquals(s, s2);
12 | }
13 |
14 | public void testInts() throws Exception {
15 | String s = "[1,2,3]";
16 | int[] bs = new int[] { 1, 2, 3 };
17 | String s2 = JSONValue.toJSONString(bs);
18 | assertEquals(s, s2);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/parent/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | net.minidev
5 | parent
6 | 1.3.2
7 | Minidev public super pom
8 | minidev common properties.
9 | pom
10 | https://urielch.github.io/
11 |
12 |
13 | Chemouni Uriel
14 | https://urielch.github.io/
15 |
16 |
17 |
18 |
19 | uriel
20 | Uriel Chemouni
21 | uchemouni@gmail.com
22 | GMT+3
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | The Apache Software License, Version 2.0
31 | http://www.apache.org/licenses/LICENSE-2.0.txt
32 | repo
33 | All files under Apache 2
34 |
35 |
36 |
37 |
38 | UTF-8
39 | 1.6
40 | 1.6
41 |
42 |
43 |
44 |
45 |
46 | org.apache.maven.plugins
47 | maven-source-plugin
48 | 3.2.1
49 |
50 |
51 | bind-sources
52 |
53 | jar
54 |
55 |
56 |
57 |
58 |
59 |
60 | org.apache.maven.plugins
61 | maven-compiler-plugin
62 | 3.8.1
63 |
64 | UTF-8
65 | 1.6
66 | 1.6
67 |
68 | **/.svn/*
69 | **/.svn
70 |
71 |
72 |
73 |
74 |
75 | org.apache.maven.plugins
76 | maven-resources-plugin
77 | 2.5
78 |
79 | UTF-8
80 |
81 |
82 |
83 |
84 | org.apache.maven.plugins
85 | maven-jar-plugin
86 | 3.2.0
87 |
88 |
89 | **/.svn/*
90 | **/.svn
91 |
92 |
93 |
94 |
95 |
96 | org.apache.maven.plugins
97 | maven-javadoc-plugin
98 | 3.2
99 |
100 |
106 |
107 |
108 | attach-javadocs
109 |
110 | jar
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 | scm:git:https://github.com/netplex/json-smart-v1.git
121 | scm:git:https://github.com/netplex/json-smart-v1.git
122 | https://github.com/netplex/json-smart-v1
123 |
124 |
125 |
126 |
127 |
128 | org.apache.maven.plugins
129 | maven-checkstyle-plugin
130 | 3.1.2
131 |
132 | config/sun_checks.xml
133 |
134 |
135 |
136 |
137 |
138 |
139 | ../json-smart
140 | ../json-smart-mini
141 |
142 |
143 |
144 |
145 |
146 | sonatype-nexus-staging
147 | Nexus Release Repository
148 | https://oss.sonatype.org/service/local/staging/deploy/maven2/
149 |
150 |
151 | sonatype-nexus-snapshots
152 | My Nexus Snapshots Repository
153 | https://oss.sonatype.org/content/repositories/snapshots/
154 |
155 |
156 |
157 |
158 |
159 | release-sign-artifacts
160 |
161 |
162 |
163 | performRelease
164 | true
165 |
166 |
167 |
168 |
169 |
170 | 53BE126D
171 |
172 |
173 |
174 |
175 |
176 |
187 |
188 | org.apache.maven.plugins
189 | maven-gpg-plugin
190 |
191 | 1.6
192 |
193 |
194 | sign-artifacts
195 | verify
196 |
197 | sign
198 |
199 |
200 |
201 |
202 |
203 |
204 | org.apache.maven.plugins
205 | maven-javadoc-plugin
206 | 3.2.0
207 |
208 |
209 | attach-javadocs
210 |
211 | jar
212 |
213 |
214 |
215 |
216 |
220 |
221 | org.apache.maven.plugins
222 | maven-release-plugin
223 | 3.0.0-M1
224 |
225 |
226 |
227 |
228 |
229 | include-sources
230 |
231 |
232 |
233 | /
234 | true
235 | src/main/java
236 |
237 | **/*.java
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 | net.minidev
248 | json-smart
249 | ${project.version}
250 |
251 |
252 | net.minidev
253 | json-smart-mini
254 | ${project.version}
255 |
256 |
257 | junit
258 | junit
259 | [4.13.2,)
260 |
261 |
262 |
263 |
264 |
--------------------------------------------------------------------------------