View Javadoc

1   /**
2    *       Copyright 2010 Newcastle University
3    *
4    *          http://research.ncl.ac.uk/smart/
5    *
6    * Licensed to the Apache Software Foundation (ASF) under one or more
7    * contributor license agreements.  See the NOTICE file distributed with
8    * this work for additional information regarding copyright ownership.
9    * The ASF licenses this file to You under the Apache License, Version 2.0
10   * (the "License"); you may not use this file except in compliance with
11   * the License.  You may obtain a copy of the License at
12   *
13   *      http://www.apache.org/licenses/LICENSE-2.0
14   *
15   * Unless required by applicable law or agreed to in writing, software
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   */
21  
22  package org.apache.amber.oauth2.common.utils;
23  
24  import java.util.HashMap;
25  import java.util.Iterator;
26  import java.util.Map;
27  
28  import org.codehaus.jettison.json.JSONException;
29  import org.codehaus.jettison.json.JSONObject;
30  
31  /**
32   *
33   *
34   *
35   */
36  public final class JSONUtils {
37  
38      public static String buildJSON(Map<String, Object> params) throws JSONException {
39          JSONObject jsonObject = new JSONObject();
40          for (Map.Entry<String, Object> param : params.entrySet()) {
41              if (param.getKey() != null && !"".equals(param.getKey()) && param.getValue() != null && !""
42                  .equals(param.getValue())) {
43                  jsonObject.put(param.getKey(), param.getValue());
44              }
45          }
46  
47          return jsonObject.toString();
48      }
49  
50      public static Map<String, Object> parseJSON(String jsonBody) throws JSONException {
51  
52          Map<String, Object> params = new HashMap<String, Object>();
53          JSONObject obj = new JSONObject(jsonBody);
54          Iterator it = obj.keys();
55          while (it.hasNext()) {
56              Object o = it.next();
57              if (o instanceof String) {
58                  String key = (String)o;
59                  params.put(key, obj.get(key));
60              }
61          }
62          return params;
63      }
64  
65  }