com.sun.faces.util.Json Maven / Gradle / Ivy
Show all versions of javax.faces Show documentation
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2016 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.util;
import static com.sun.faces.util.Json.Option.SKIP_NULL_VALUES;
import static com.sun.faces.util.Json.Option.USE_RFC1123_DATE;
import static java.time.ZoneOffset.UTC;
import static java.time.format.DateTimeFormatter.ISO_INSTANT;
import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME;
import static java.util.Arrays.asList;
import static java.util.EnumSet.copyOf;
import static java.util.EnumSet.noneOf;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.Map;
import java.util.Map.Entry;
import javax.json.stream.JsonGenerator;
/**
*
* Generic JSON encoder using javax.json API.
*
* This supports the standard types {@link Boolean}, {@link Number}, {@link Character}, {@link CharSequence},
* {@link Date}, {@link LocalDate} and {@link Instant}.
* If the given object type does not match any of them, then it will attempt to inspect the object as a JavaBean
* using the {@link Introspector}, whereby the public properties (public getters) will be encoded as a JS object.
* It also supports arrays, {@link Collection}s and {@link Map}s of them, even nested ones.
* The dates are formatted as ISO8601 instant via {@link DateTimeFormatter#ISO_INSTANT}, so you can if necessary
* just pass the value straight to new Date(value)
in JavaScript.
*
* Below encoding options are available:
*
{@link Option#SKIP_NULL_VALUES}: skip null values in arrays, collections, maps and beans.
* This may reduce an unnecessarily bloated JSON object.
* {@link Option#USE_RFC1123_DATE}: format dates as RFC1123 via {@link DateTimeFormatter#RFC_1123_DATE_TIME}.
* This may improve compatibility with older web browsers.
*
* @author Bauke Scholtz
* @since 2.3
*/
public class Json {
private static final String ERROR_INVALID_BEAN = "Cannot introspect object of type '%s' as bean.";
private static final String ERROR_INVALID_GETTER = "Cannot invoke getter of property '%s' of bean '%s'.";
public enum Option {
/**
* Skip null values in arrays, collections, maps and beans.
* This may reduce an unnecessarily bloated JSON object.
*/
SKIP_NULL_VALUES,
/**
* Format dates as RFC1123 via {@link DateTimeFormatter#RFC_1123_DATE_TIME}.
* This may improve compatibility with older web browsers.
*/
USE_RFC1123_DATE;
}
/**
* Encodes the given object as JSON and returns a string in JSON format.
* The encoded object will be available as data
property of the JS object in the returned JSON string.
*
* @param object The object to be encoded as JSON.
* @param options The encoding options.
* @return The JSON-encoded representation of the given object.
* @throws IllegalArgumentException When given object or one of its properties cannot be inspected as a JavaBean.
*/
public static String encode(Object object, Option... options) {
StringWriter writer = new StringWriter();
encode(object, writer, options);
return writer.toString();
}
/**
* Encodes the given object as JSON while streaming the string in JSON format to the given writer.
* The encoded object will be available as data
property of the JS object in the returned JSON string.
*
* @param object The object to be encoded as JSON.
* @param writer The writer to stream the encoded output to.
* @param options The encoding options.
* @throws IllegalArgumentException When given object or one of its properties cannot be inspected as a JavaBean.
*/
public static void encode(Object object, Writer writer, Option... options) {
try (JsonGenerator generator = javax.json.Json.createGenerator(writer)) {
generator.writeStartObject();
encode("data", object, generator, options.length == 0 ? noneOf(Option.class) : copyOf(asList(options)));
generator.writeEnd();
}
}
private static void encode(String name, Object object, JsonGenerator generator, EnumSet