1 | // Copyright (C) 2008 Google Inc. |
2 | // |
3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | // you may not use this file except in compliance with the License. |
5 | // You may obtain a copy of the License at |
6 | // |
7 | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | // |
9 | // Unless required by applicable law or agreed to in writing, software |
10 | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | // See the License for the specific language governing permissions and |
13 | // limitations under the License. |
14 | |
15 | package com.google.caja.util; |
16 | |
17 | import org.json.simple.JSONArray; |
18 | import org.json.simple.JSONObject; |
19 | /** |
20 | * Utility class for manipulating JSON objects |
21 | * |
22 | * @author jasvir@google.com (Jasvir Nagra) |
23 | * |
24 | */ |
25 | public class Json { |
26 | public static JSONObject formatAsJson(Object... members) { |
27 | JSONObject o = new JSONObject(); |
28 | putJson(o, members); |
29 | return o; |
30 | } |
31 | |
32 | @SuppressWarnings("unchecked") |
33 | public static void putJson(JSONObject o, Object... members) { |
34 | for (int i = 0, n = members.length; i < n; i += 2) { |
35 | String name = (String) members[i]; |
36 | Object value = toJsonValue(members[i + 1]); |
37 | o.put(name, value); |
38 | } |
39 | } |
40 | |
41 | @SuppressWarnings("unchecked") |
42 | public static void pushJson(JSONArray a, Object... members) { |
43 | for (Object member : members) { |
44 | a.add(toJsonValue(member)); |
45 | } |
46 | } |
47 | |
48 | public static Object toJsonValue(Object value) { |
49 | if (value == null || value instanceof Boolean || value instanceof Number |
50 | || value instanceof JSONObject || value instanceof JSONArray) { |
51 | return value; |
52 | } |
53 | return value.toString(); |
54 | } |
55 | } |