001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, by Object Refinery Limited and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 * --------------
028 * JSONUtils.java
029 * --------------
030 * (C) Copyright 2014-2016, by Object Refinery Limited.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   -;
034 *
035 */
036
037package org.jfree.data.json;
038
039import java.io.IOException;
040import java.io.StringWriter;
041import java.io.Writer;
042import java.util.Iterator;
043import java.util.List;
044import org.jfree.chart.util.Args;
045import org.jfree.data.KeyedValues;
046import org.jfree.data.KeyedValues2D;
047import org.jfree.data.category.CategoryDataset;
048import org.jfree.data.general.PieDataset;
049import org.jfree.data.json.impl.JSONValue;
050
051/**
052 * A utility class that can read and write data in specific JSON formats.
053 * 
054 * @since 1.0.20
055 */
056public class JSONUtils {
057
058    /**
059     * Returns a string containing the data in JSON format.  The format is
060     * an array of arrays, where each sub-array represents one data value.
061     * The sub-array should contain two items, first the item key as a string
062     * and second the item value as a number.  For example:
063     * {@code [["Key A", 1.0], ["Key B", 2.0]]}
064     * <br><br>
065     * Note that this method can be used with instances of {@link PieDataset}.
066     * 
067     * @param data  the data ({@code null} not permitted).
068     * 
069     * @return A string in JSON format. 
070     */
071    public static String writeKeyedValues(KeyedValues data) {
072        Args.nullNotPermitted(data, "data");
073        StringWriter sw = new StringWriter();
074        try {
075            writeKeyedValues(data, sw);
076        } catch (IOException ex) {
077            throw new RuntimeException(ex);
078        }
079        return sw.toString();
080    }
081
082    /**
083     * Writes the data in JSON format to the supplied writer.
084     * <br><br>
085     * Note that this method can be used with instances of {@link PieDataset}.
086     * 
087     * @param data  the data ({@code null} not permitted).
088     * @param writer  the writer ({@code null} not permitted).
089     * 
090     * @throws IOException if there is an I/O problem.
091     */
092    public static void writeKeyedValues(KeyedValues data, Writer writer) 
093            throws IOException {
094        Args.nullNotPermitted(data, "data");
095        Args.nullNotPermitted(writer, "writer");
096        writer.write("[");
097        boolean first = true;
098        Iterator iterator = data.getKeys().iterator();
099        while (iterator.hasNext()) {
100            Comparable key = (Comparable) iterator.next();
101            if (!first) {
102                writer.write(", ");
103            } else {
104                first = false;
105            }
106            writer.write("[");
107            writer.write(JSONValue.toJSONString(key.toString()));
108            writer.write(", ");
109            writer.write(JSONValue.toJSONString(data.getValue(key)));
110            writer.write("]");
111        }
112        writer.write("]");
113    }
114    
115    /**
116     * Returns a string containing the data in JSON format.  The format is...
117     * <br><br>
118     * Note that this method can be used with instances of 
119     * {@link CategoryDataset}.
120     * 
121     * @param data  the data ({@code null} not permitted).
122     * 
123     * @return A string in JSON format. 
124     */
125    public static String writeKeyedValues2D(KeyedValues2D data) {
126        Args.nullNotPermitted(data, "data");
127        StringWriter sw = new StringWriter();
128        try {
129            writeKeyedValues2D(data, sw);
130        } catch (IOException ex) {
131            throw new RuntimeException(ex);
132        }
133        return sw.toString();
134    }
135
136    /**
137     * Writes the data in JSON format to the supplied writer.
138     * <br><br>
139     * Note that this method can be used with instances of 
140     * {@link CategoryDataset}.
141     * 
142     * @param data  the data ({@code null} not permitted).
143     * @param writer  the writer ({@code null} not permitted).
144     * 
145     * @throws IOException if there is an I/O problem.
146     */
147    public static void writeKeyedValues2D(KeyedValues2D data, Writer writer) 
148            throws IOException {
149        Args.nullNotPermitted(data, "data");
150        Args.nullNotPermitted(writer, "writer");
151        List<Comparable<?>> columnKeys = data.getColumnKeys();
152        List<Comparable<?>> rowKeys = data.getRowKeys();
153        writer.write("{");
154        if (!columnKeys.isEmpty()) {
155            writer.write("\"columnKeys\": [");
156            boolean first = true;
157            for (Comparable<?> columnKey : columnKeys) {
158                if (!first) {
159                    writer.write(", ");
160                } else {
161                    first = false;
162                }
163                writer.write(JSONValue.toJSONString(columnKey.toString()));
164            }
165            writer.write("]");
166        }
167        if (!rowKeys.isEmpty()) {
168            writer.write(", \"rows\": [");
169            boolean firstRow = true;
170            for (Comparable<?> rowKey : rowKeys) {   
171                if (!firstRow) {
172                    writer.write(", [");
173                } else {
174                    writer.write("[");
175                    firstRow = false;
176                }
177                // write the row data 
178                writer.write(JSONValue.toJSONString(rowKey.toString()));
179                writer.write(", [");
180                boolean first = true;
181                for (Comparable<?> columnKey : columnKeys) {
182                    if (!first) {
183                        writer.write(", ");
184                    } else {
185                        first = false;
186                    }
187                    writer.write(JSONValue.toJSONString(data.getValue(rowKey, 
188                            columnKey)));
189                }
190                writer.write("]]");
191            }
192            writer.write("]");
193        }
194        writer.write("}");    
195    }
196    
197}