View Javadoc

1   /*--------------------------------------------------------------------------
2    *  Copyright 2007 utgenome.org
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   *--------------------------------------------------------------------------*/
16  //--------------------------------------
17  // GenomeBrowser Project
18  //
19  // JSONUtil.java
20  // Since: Jul 23, 2007
21  //
22  // $URL$ 
23  // $Author$
24  //--------------------------------------
25  package org.utgenome.gwt.utgb.client.util;
26  
27  import java.util.ArrayList;
28  import java.util.Iterator;
29  import java.util.List;
30  
31  import com.google.gwt.json.client.JSONArray;
32  import com.google.gwt.json.client.JSONParser;
33  import com.google.gwt.json.client.JSONString;
34  import com.google.gwt.json.client.JSONValue;
35  
36  public class JSONUtil {
37  
38  	/**
39  	 * Non constractable
40  	 */
41  	private JSONUtil() {
42  	}
43  
44  	/**
45  	 * Create a JSONArray string from the given iterable list
46  	 * 
47  	 * @param iterable
48  	 * @return
49  	 */
50  	public static <T> String toJSONArray(List<T> iterable) {
51  		JSONArray array = new JSONArray();
52  		int index = 0;
53  		for (Iterator<T> it = iterable.iterator(); it.hasNext();) {
54  			array.set(index++, new JSONString(it.next().toString()));
55  		}
56  		return array.toString();
57  	}
58  
59  	public static ArrayList<String> parseJSONArray(String jsonArray) {
60  		if (jsonArray == null)
61  			return new ArrayList<String>();
62  
63  		if (!jsonArray.startsWith("[") || !jsonArray.endsWith("]"))
64  			throw new IllegalArgumentException("invalid json array data");
65  
66  		ArrayList<String> elementList = new ArrayList<String>();
67  		JSONValue v = JSONParser.parse(jsonArray);
68  		JSONArray array = v.isArray();
69  		if (array != null) {
70  			for (int i = 0; i < array.size(); i++)
71  				elementList.add(toStringValue(array.get(i)));
72  		}
73  		return elementList;
74  	}
75  
76  	/**
77  	 * Get a string value (without double quotation) of JSONString, or other JSON types.
78  	 * 
79  	 * @param value
80  	 * @return
81  	 */
82  	public static String toStringValue(JSONValue value) {
83  		if (value == null)
84  			return "";
85  
86  		JSONString str = value.isString();
87  		if (str != null)
88  			return str.stringValue();
89  		else
90  			return value.toString();
91  	}
92  
93  }