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 * Changes:
036 * --------
037 * 04-Aug-2014 : Version 1 (DG);
038 *
039 */
040
041package org.jfree.data.json;
042
043import java.io.IOException;
044import java.io.StringWriter;
045import java.io.Writer;
046import java.util.Iterator;
047import java.util.List;
048import org.jfree.chart.util.Args;
049import org.jfree.data.KeyedValues;
050import org.jfree.data.KeyedValues2D;
051import org.jfree.data.category.CategoryDataset;
052import org.jfree.data.general.PieDataset;
053import org.jfree.data.json.impl.JSONValue;
054
055/**
056 * A utility class that can read and write data in specific JSON formats.
057 * 
058 * @since 1.0.20
059 */
060public class JSONUtils {
061
062    /**
063     * Returns a string containing the data in JSON format.  The format is
064     * an array of arrays, where each sub-array represents one data value.
065     * The sub-array should contain two items, first the item key as a string
066     * and second the item value as a number.  For example:
067     * {@code [["Key A", 1.0], ["Key B", 2.0]]}
068     * <br><br>
069     * Note that this method can be used with instances of {@link PieDataset}.
070     * 
071     * @param data  the data ({@code null} not permitted).
072     * 
073     * @return A string in JSON format. 
074     */
075    public static String writeKeyedValues(KeyedValues data) {
076        Args.nullNotPermitted(data, "data");
077        StringWriter sw = new StringWriter();
078        try {
079            writeKeyedValues(data, sw);
080        } catch (IOException ex) {
081            throw new RuntimeException(ex);
082        }
083        return sw.toString();
084    }
085
086    /**
087     * Writes the data in JSON format to the supplied writer.
088     * <br><br>
089     * Note that this method can be used with instances of {@link PieDataset}.
090     * 
091     * @param data  the data ({@code null} not permitted).
092     * @param writer  the writer ({@code null} not permitted).
093     * 
094     * @throws IOException if there is an I/O problem.
095     */
096    public static void writeKeyedValues(KeyedValues data, Writer writer) 
097            throws IOException {
098        Args.nullNotPermitted(data, "data");
099        Args.nullNotPermitted(writer, "writer");
100        writer.write("[");
101        boolean first = true;
102        Iterator iterator = data.getKeys().iterator();
103        while (iterator.hasNext()) {
104            Comparable key = (Comparable) iterator.next();
105            if (!first) {
106                writer.write(", ");
107            } else {
108                first = false;
109            }
110            writer.write("[");
111            writer.write(JSONValue.toJSONString(key.toString()));
112            writer.write(", ");
113            writer.write(JSONValue.toJSONString(data.getValue(key)));
114            writer.write("]");
115        }
116        writer.write("]");
117    }
118    
119    /**
120     * Returns a string containing the data in JSON format.  The format is...
121     * <br><br>
122     * Note that this method can be used with instances of 
123     * {@link CategoryDataset}.
124     * 
125     * @param data  the data ({@code null} not permitted).
126     * 
127     * @return A string in JSON format. 
128     */
129    public static String writeKeyedValues2D(KeyedValues2D data) {
130        Args.nullNotPermitted(data, "data");
131        StringWriter sw = new StringWriter();
132        try {
133            writeKeyedValues2D(data, sw);
134        } catch (IOException ex) {
135            throw new RuntimeException(ex);
136        }
137        return sw.toString();
138    }
139
140    /**
141     * Writes the data in JSON format to the supplied writer.
142     * <br><br>
143     * Note that this method can be used with instances of 
144     * {@link CategoryDataset}.
145     * 
146     * @param data  the data ({@code null} not permitted).
147     * @param writer  the writer ({@code null} not permitted).
148     * 
149     * @throws IOException if there is an I/O problem.
150     */
151    public static void writeKeyedValues2D(KeyedValues2D data, Writer writer) 
152            throws IOException {
153        Args.nullNotPermitted(data, "data");
154        Args.nullNotPermitted(writer, "writer");
155        List<Comparable<?>> columnKeys = data.getColumnKeys();
156        List<Comparable<?>> rowKeys = data.getRowKeys();
157        writer.write("{");
158        if (!columnKeys.isEmpty()) {
159            writer.write("\"columnKeys\": [");
160            boolean first = true;
161            for (Comparable<?> columnKey : columnKeys) {
162                if (!first) {
163                    writer.write(", ");
164                } else {
165                    first = false;
166                }
167                writer.write(JSONValue.toJSONString(columnKey.toString()));
168            }
169            writer.write("]");
170        }
171        if (!rowKeys.isEmpty()) {
172            writer.write(", \"rows\": [");
173            boolean firstRow = true;
174            for (Comparable<?> rowKey : rowKeys) {   
175                if (!firstRow) {
176                    writer.write(", [");
177                } else {
178                    writer.write("[");
179                    firstRow = false;
180                }
181                // write the row data 
182                writer.write(JSONValue.toJSONString(rowKey.toString()));
183                writer.write(", [");
184                boolean first = true;
185                for (Comparable<?> columnKey : columnKeys) {
186                    if (!first) {
187                        writer.write(", ");
188                    } else {
189                        first = false;
190                    }
191                    writer.write(JSONValue.toJSONString(data.getValue(rowKey, 
192                            columnKey)));
193                }
194                writer.write("]]");
195            }
196            writer.write("]");
197        }
198        writer.write("}");    
199    }
200    
201}