1 package atg.taglib.json.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 import java.util.Iterator;
28
29 /**
30 * Convert a web browser cookie list string to a JSONObject and back.
31 * @author JSON.org
32 * @version 2
33 */
34 public class CookieList {
35
36 /**
37 * Convert a cookie list into a JSONObject. A cookie list is a sequence
38 * of name/value pairs. The names are separated from the values by '='.
39 * The pairs are separated by ';'. The names and the values
40 * will be unescaped, possibly converting '+' and '%' sequences.
41 *
42 * To add a cookie to a cooklist,
43 * cookielistJSONObject.put(cookieJSONObject.getString("name"),
44 * cookieJSONObject.getString("value"));
45 * @param string A cookie list string
46 * @return A JSONObject
47 * @throws JSONException
48 */
49 public static JSONObject toJSONObject(String string) throws JSONException {
50 JSONObject o = new JSONObject();
51 JSONTokener x = new JSONTokener(string);
52 while (x.more()) {
53 String name = Cookie.unescape(x.nextTo('='));
54 x.next('=');
55 o.put(name, Cookie.unescape(x.nextTo(';')));
56 x.next();
57 }
58 return o;
59 }
60
61
62 /**
63 * Convert a JSONObject into a cookie list. A cookie list is a sequence
64 * of name/value pairs. The names are separated from the values by '='.
65 * The pairs are separated by ';'. The characters '%', '+', '=', and ';'
66 * in the names and values are replaced by "%hh".
67 * @param o A JSONObject
68 * @return A cookie list string
69 * @throws JSONException
70 */
71 public static String toString(JSONObject o) throws JSONException {
72 boolean b = false;
73 Iterator keys = o.keys();
74 String s;
75 StringBuffer sb = new StringBuffer();
76 while (keys.hasNext()) {
77 s = keys.next().toString();
78 if (!o.isNull(s)) {
79 if (b) {
80 sb.append(';');
81 }
82 sb.append(Cookie.escape(s));
83 sb.append("=");
84 sb.append(Cookie.escape(o.getString(s)));
85 b = true;
86 }
87 }
88 return sb.toString();
89 }
90 }