JSON refactoring
[jalview.git] / src / jalview / util / JSONUtils.java
1 package jalview.util;
2
3 import jalview.javascript.json.JSON;
4
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.io.Reader;
8 import java.util.List;
9
10 import org.json.simple.parser.JSONParser;
11 import org.json.simple.parser.ParseException;
12
13 public class JSONUtils
14 {
15
16   /**
17    * Converts a JSONArray of values to a string as a comma-separated list.
18    * Answers null if the array is null or empty.
19    * 
20    * @param jsonArray
21    * @return
22    */
23   public static String arrayToStringList(List<Object> jsonArray)
24   {
25         int n;
26         
27     if (jsonArray == null || (n = jsonArray.size()) == 0)
28     {
29       return null;
30     }
31
32     /**
33      * @j2sNative
34      * 
35      * return jsonArray.elementData.slice(0, n).join(",");
36      */
37     {
38             StringBuilder sb = new StringBuilder();
39             for (int i = 0; i < n; i++)
40             {
41               if (i > 0)
42               {
43                 sb.append(",");
44               }
45               sb.append(jsonArray.get(i).toString());
46             }
47             return sb.toString();
48     }
49   }
50
51   /**
52    * The method all JSON parsing must go through for JavaScript. 
53    * @param r a BufferedReader or a javascript.json.JSON.JSONReader
54    * @return
55    * @throws IOException
56    * @throws ParseException
57    */
58   public static Object parse(Reader r) throws IOException, ParseException 
59   {
60       // Using a file reader is not currently supported in SwingJS JavaScript
61
62           if (r == null)
63                   return null;
64 //        
65 //              Platform.timeCheck("JSONUtils.parse0 ", Platform.TIME_MARK);
66
67         Object ret;    
68         if (Platform.isJS()) 
69         {
70           if (r instanceof FileReader) 
71           {
72             throw new IOException("StringJS does not support FileReader parsing for JSON -- but it could...");
73           }
74           return JSON.parse(r);
75         } else {
76          ret = new JSONParser().parse(r);
77         }
78 //      Platform.timeCheck("JSONUtils.parse1 ", Platform.TIME_MARK);
79         return ret;
80   }
81
82   public static Object parse(String json) throws ParseException 
83   {
84         return (Platform.isJS() ? JSON.parse(json) : new JSONParser().parse(json));
85   }
86
87 }