#210 Fixes Ensembl fetch problem (really)
[jalview.git] / src / jalview / util / JSONUtils.java
1 package jalview.util;
2
3 import java.io.IOException;
4 import java.io.Reader;
5 import java.util.List;
6
7 import org.json.simple.parser.ParseException;
8
9 public class JSONUtils
10 {
11
12   /**
13    * Converts a JSONArray of values to a string as a comma-separated list.
14    * Answers null if the array is null or empty.
15    * 
16    * @param jsonArray
17    * @return
18    */
19   public static String arrayToStringList(List<Object> jsonArray)
20   {
21     int n;
22
23     if (jsonArray == null || (n = jsonArray.size()) == 0)
24     {
25       return null;
26     }
27
28     /**
29      * @j2sNative
30      * 
31      *            return jsonArray.elementData.slice(0, n).join(",");
32      */
33     {
34       StringBuilder sb = new StringBuilder();
35       for (int i = 0; i < n; i++)
36       {
37         if (i > 0)
38         {
39           sb.append(",");
40         }
41         sb.append(jsonArray.get(i).toString());
42       }
43       return sb.toString();
44     }
45   }
46
47   /**
48    * The method all JSON parsing must go through for JavaScript.
49    * 
50    * @param r
51    *          a BufferedReader or a javascript.json.JSON.JSONReader
52    * @return
53    * @throws IOException
54    * @throws ParseException
55    */
56   public static Object parse(Reader r) throws IOException, ParseException
57   {
58     return Platform.parseJSON(r);
59   }
60
61   public static Object parse(String json) throws ParseException
62   {
63     return Platform.parseJSON(json);
64   }
65
66   public static String stringify(Object obj)
67   {
68     return new org.json.JSONObject(obj).toString();
69   }
70
71 }