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