Example usage for com.google.gson JsonElement getAsJsonArray

List of usage examples for com.google.gson JsonElement getAsJsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsJsonArray.

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

From source file:com.github.GsonPrettyPrinter.java

License:Open Source License

private List<String> toStringList(final JsonElement je) {
    if (je == null || je.isJsonNull())
        return new ArrayList<String>(Arrays.asList(new String[] { "null" }));
    if (je.isJsonPrimitive())
        return Collections.singletonList(je.getAsJsonPrimitive().toString());
    if (je.isJsonArray()) {
        final JsonArray jsonArray = je.getAsJsonArray();
        return arrayToStringList(jsonArray);
    } else if (je.isJsonObject()) {
        final JsonObject jsonObject = je.getAsJsonObject();
        return objectToStringList(jsonObject);
    }/* w w  w.  j  av  a2s .co m*/
    throw new RuntimeException("Unsupported Json element: " + je.getClass().getName());
}

From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java

License:Apache License

private List<String> getAuthorities(JsonObject userObject) {
    List<String> authorities = new ArrayList<String>();
    if (!userObject.has(AUTHORITIES)) {
        throw new AlfrescoParseException("Json response is authorities.");
    }/*from w w  w .  j a va2  s .  c  om*/
    JsonElement authoritiesElement = userObject.get(AUTHORITIES);
    if (!authoritiesElement.isJsonArray()) {
        throw new AlfrescoParseException(
                "Authorities must be a json array. It was: " + authoritiesElement.toString());
    }
    JsonArray authoritiesArray = authoritiesElement.getAsJsonArray();
    for (JsonElement authorityElement : authoritiesArray) {
        if (!authorityElement.isJsonPrimitive()) {
            throw new AlfrescoParseException(
                    "Authority entry must be a string. It was: " + authoritiesElement.toString());
        }
        JsonPrimitive authorityPrimitive = authorityElement.getAsJsonPrimitive();
        if (!authorityPrimitive.isString()) {
            throw new AlfrescoParseException(
                    "Authority entry must be a string. It was: " + authoritiesElement.toString());
        }
        authorities.add(authorityPrimitive.getAsString());
    }
    return authorities;
}

From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java

License:Apache License

private List<AlfrescoUser> usersFromHttpEntity(HttpEntity entity) throws IOException {
    Reader entityReader = new InputStreamReader(entity.getContent());
    JsonElement responseObject = gson.fromJson(entityReader, JsonElement.class);
    if (!responseObject.isJsonArray()) {
        throw new AlfrescoParseException("Users must be a json array.");
    }/*from ww  w. ja va2  s.  com*/
    List<AlfrescoUser> users = new ArrayList<AlfrescoUser>();
    JsonArray usersArray = responseObject.getAsJsonArray();
    for (JsonElement userElement : usersArray) {
        if (!userElement.isJsonObject()) {
            throw new AlfrescoParseException("User must be a json object.");
        }
        AlfrescoUser user = getUser(userElement.getAsJsonObject());
        users.add(user);
    }
    return users;
}

From source file:com.github.nyrkovalex.deploy.me.parsing.Parser.java

License:Open Source License

@Override
public Script parse(String path, JsonElement locations) {
    Iterable<String> targets = locations.isJsonArray()
            ? FluentIterable.from(locations.getAsJsonArray()).transform(item -> item.getAsString()).toSet()
            : ImmutableSet.of(locations.getAsString());
    return new Script(path, targets);
}

From source file:com.github.playerforcehd.gcaptchavalidator.captchaverification.CaptchaValidationResult.java

License:Open Source License

/**
 * Deserialize a result from the Google SiteKey servers
 *
 * @param json The JSon to deserialize/*from w  w  w  .  j  a  v  a  2  s. c o m*/
 * @return The result of the deserialization
 */
static CaptchaValidationResult deserializeJSon(String json) {
    JsonElement jsonElement = new JsonParser().parse(json);
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    boolean success = jsonObject.get("success").getAsBoolean();
    String challengeTS = null;
    if (jsonObject.get("challenge_ts") != null) {
        challengeTS = jsonObject.get("challenge_ts").getAsString();
    }
    String hostName = null;
    if (jsonObject.get("hostname") != null) {
        hostName = jsonObject.get("hostname").getAsString();
    }
    Collection<CaptchaValidationError> errorCodes = new ArrayList<>();
    if (jsonObject.get("error-codes") != null) {
        JsonElement errorList = jsonObject.get("error-codes");
        for (int i = errorList.getAsJsonArray().size() - 1; i >= 0; i--) {
            errorCodes.add(CaptchaValidationError
                    .parseGoogleJSonErrorCode(errorList.getAsJsonArray().get(i).getAsString()));
        }
    }
    return new CaptchaValidationResult(success, challengeTS, hostName, errorCodes);
}

From source file:com.github.rustdt.tooling.RustJsonMessageParser.java

License:Open Source License

protected ArrayList2<String> parseNotes(JsonElement children) throws CommonException {
    ArrayList2<String> notes = new ArrayList2<>();
    if (children == null || !children.isJsonArray()) {
        return notes;
    }/*  w  w  w  .j a v a  2s .  c  om*/
    JsonArray childrenArray = children.getAsJsonArray();
    if (childrenArray.size() == 0) {
        return notes;
    }
    for (JsonElement child : childrenArray) {
        if (child.isJsonObject()) {
            String childMessageString = helper.getOptionalString(child.getAsJsonObject(), "message");
            if (childMessageString != null && !childMessageString.isEmpty()) {
                notes.add(childMessageString);
            }
        }
    }
    return notes;
}

From source file:com.github.thesmartenergy.sparql.generate.jena.function.library.FN_CBOR.java

License:Apache License

/**
 *
 * @param cbor a RDF Literal with datatype URI
 * {@code <urn:iana:mime:application/cbor>} or {@code xsd:string}
 * @param jsonpath a RDF Literal with datatype {@code xsd:string}
 * @return a RDF Literal with datatype URI
 * {@code <urn:iana:mime:application/json>}
 *///from w  ww  . j  a va2 s . c o  m
@Override
public NodeValue exec(NodeValue cbor, NodeValue jsonpath) {

    if (cbor.getDatatypeURI() == null && datatypeUri == null
            || cbor.getDatatypeURI() != null && !cbor.getDatatypeURI().equals(datatypeUri)
                    && !cbor.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) {
        LOG.warn("The URI of NodeValue1 MUST be <" + datatypeUri + ">"
                + "or <http://www.w3.org/2001/XMLSchema#string>." + " Returning null.");
    }

    String json = new String(Base64.getDecoder().decode(cbor.asNode().getLiteralLexicalForm().getBytes()));
    try {
        Object value = JsonPath.parse(json).limit(1).read(jsonpath.getString());

        if (value instanceof String) {
            return new NodeValueString((String) value);
        } else if (value instanceof Float) {
            return new NodeValueFloat((Float) value);
        } else if (value instanceof Boolean) {
            return new NodeValueBoolean((Boolean) value);
        } else if (value instanceof Integer) {
            return new NodeValueInteger((Integer) value);
        } else if (value instanceof Double) {
            return new NodeValueDouble((Double) value);
        } else if (value instanceof BigDecimal) {
            return new NodeValueDecimal((BigDecimal) value);
        } else {
            String strValue = String.valueOf(value);

            JsonParser parser = new JsonParser();
            JsonElement valElement = parser.parse(strValue);
            JsonArray list = valElement.getAsJsonArray();

            if (list.size() == 1) {
                String jsonstring = list.get(0).getAsString();
                Node node = NodeFactory.createLiteral(jsonstring);
                NodeValue nodeValue = new NodeValueNode(node);
                return nodeValue;

            } else {
                return new NodeValueString(String.valueOf(value));
            }
        }
    } catch (Exception e) {
        throw new ExprEvalException("FunctionBase: no evaluation", e);
    }
}

From source file:com.github.thesmartenergy.sparql.generate.jena.function.library.FN_JSONPath.java

License:Apache License

/**
 *
 * @param json a RDF Literal with datatype URI
 * {@code <urn:iana:mime:application/json>} or {@code xsd:string}
 * @param jsonpath a RDF Literal with datatype {@code xsd:string}
 * @return a RDF Literal with datatype being the type of the object
 * extracted from the JSON document//w w  w  . j  a  v  a  2  s.c  o  m
 */
@Override
public NodeValue exec(NodeValue json, NodeValue jsonpath) {
    if (json.getDatatypeURI() == null && datatypeUri == null
            || json.getDatatypeURI() != null && !json.getDatatypeURI().equals(datatypeUri)
                    && !json.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) {
        LOG.warn("The URI of NodeValue1 MUST be <" + datatypeUri + ">"
                + "or <http://www.w3.org/2001/XMLSchema#string>." + " Returning null.");
    }

    try {
        Object value = JsonPath.parse(json.asNode().getLiteralLexicalForm()).limit(1)
                .read(jsonpath.getString());

        if (value instanceof String) {
            return new NodeValueString((String) value);
        } else if (value instanceof Float) {
            return new NodeValueFloat((Float) value);
        } else if (value instanceof Boolean) {
            return new NodeValueBoolean((Boolean) value);
        } else if (value instanceof Integer) {
            return new NodeValueInteger((Integer) value);
        } else if (value instanceof Long) {
            return new NodeValueInteger((Long) value);
        } else if (value instanceof Double) {
            return new NodeValueDouble((Double) value);
        } else if (value instanceof BigDecimal) {
            return new NodeValueDecimal((BigDecimal) value);
        } else {
            String strValue = String.valueOf(value);

            JsonParser parser = new JsonParser();
            JsonElement valElement = parser.parse(strValue);
            JsonArray list = valElement.getAsJsonArray();

            if (list.size() == 1) {
                String jsonstring = list.get(0).getAsString();
                Node node = NodeFactory.createLiteral(jsonstring);
                NodeValue nodeValue = new NodeValueNode(node);
                return nodeValue;

            } else {
                return new NodeValueString(String.valueOf(value));
            }
        }
    } catch (Exception e) {
        throw new ExprEvalException("FunctionBase: no evaluation", e);
    }
}

From source file:com.github.zhizheng.json.JsonSchemaGeneratorImpl.java

License:Apache License

/**
 * ? JsonElement? Json Schema /*from ww w. j  a va2 s  . com*/
 * 
 * @param jsonElement
 * @param elementName
 * @param isFirstLevel
 * @param required
 * @return
 */
private JsonObject makeSchemaElement(JsonElement jsonElement, String elementName, boolean isFirstLevel,
        JsonArray required) {
    JsonObject jsonSchemaObject = new JsonObject();

    // id, $schema
    if (isFirstLevel) {
        if (jsonSchemaConfig.isPrintId()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.ID.toString(), jsonSchemaConfig.getId());
        }
        jsonSchemaObject.addProperty(JsonSchemaKeywords.SCHEMA.toString(), jsonSchemaConfig.getVersion());
    } else {
        if (jsonSchemaConfig.isPrintId()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.ID.toString(), "/" + elementName);
        }
    }

    // title
    if (jsonSchemaConfig.isPrintTitle()) {
        jsonSchemaObject.addProperty(JsonSchemaKeywords.TITLE.toString(), elementName);// jsonSchemaConfig.getTitle()
    }

    // description
    if (jsonSchemaConfig.isPrintDescription()) {
        jsonSchemaObject.addProperty(JsonSchemaKeywords.DESCRIPTION.toString(),
                jsonSchemaConfig.getDescription());
    }

    // type
    String jsonElementType = JsonValueTypes.getJsonValueType(jsonElement);
    jsonSchemaObject.addProperty(JsonSchemaKeywords.TYPE.toString(), jsonElementType);
    if (jsonElementType.equals(JsonValueTypes.STRING.toString())) {// string
        if (jsonSchemaConfig.isPrintMinLength()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.MINLENGTH.toString(),
                    jsonSchemaConfig.getMinLength());
        }
        if (jsonSchemaConfig.isPrintMaxLength()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.MAXLENGTH.toString(),
                    jsonSchemaConfig.getMaxLength());
        }
        if (jsonSchemaConfig.isPrintDefault()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.DEFAULT.toString(),
                    jsonSchemaConfig.isDefaultFromJson() ? jsonElement.getAsString()
                            : jsonSchemaConfig.getDefaultString());
        }
    }
    if (jsonElementType.equals(JsonValueTypes.NUMBER.toString())) {// number
        if (jsonSchemaConfig.isPrintMinimum()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.MINIMUM.toString(), jsonSchemaConfig.getMinimum());
        }
        if (jsonSchemaConfig.isPrintMaximum()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.MAXIMUM.toString(), jsonSchemaConfig.getMaximum());
        }
        if (jsonSchemaConfig.isPrintExclusiveMinimum()) {
            if (!jsonSchemaConfig.isPrintMinimum()) {
                jsonSchemaObject.addProperty(JsonSchemaKeywords.MINIMUM.toString(),
                        jsonSchemaConfig.getMinimum());
            }
            jsonSchemaObject.addProperty(JsonSchemaKeywords.EXCLUSIVEMINIMUM.toString(),
                    jsonSchemaConfig.isExclusiveMinimum());
        }
        if (jsonSchemaConfig.isPrintExclusiveMaximum()) {
            if (!jsonSchemaConfig.isPrintMaximum()) {
                jsonSchemaObject.addProperty(JsonSchemaKeywords.MAXIMUM.toString(),
                        jsonSchemaConfig.getMaximum());
            }
            jsonSchemaObject.addProperty(JsonSchemaKeywords.EXCLUSIVEMAXIMUM.toString(),
                    jsonSchemaConfig.isExclusiveMaximum());
        }
        if (jsonSchemaConfig.isPrintDefault()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.DEFAULT.toString(),
                    jsonSchemaConfig.isDefaultFromJson() ? jsonElement.getAsNumber()
                            : jsonSchemaConfig.getDefaultNumber());
        }
    }

    // required && V3
    if (jsonSchemaConfig.isPrintRequired()
            && JsonSchemaVersions.V3.toString().equals(jsonSchemaConfig.getVersion())) {// V3 required  boolean ???
        jsonSchemaObject.addProperty(JsonSchemaKeywords.REQUIRED.toString(), jsonSchemaConfig.isRequired());
    }
    // required && V4
    if (jsonSchemaConfig.isPrintRequired()
            && JsonSchemaVersions.V4.toString().equals(jsonSchemaConfig.getVersion())
            && (jsonElementType.equals(JsonValueTypes.STRING.toString())
                    || jsonElementType.equals(JsonValueTypes.NUMBER.toString())
                    || jsonElementType.equals(JsonValueTypes.INTEGER.toString())
                    || jsonElementType.equals(JsonValueTypes.BOOLEAN.toString()))) {// V4 required  array ? object 
        required.add(elementName);
    }

    // properties, items
    JsonArray newRequired = new JsonArray();
    if (jsonElementType.equals(JsonValueTypes.OBJECT.toString())
            && !jsonElement.getAsJsonObject().entrySet().isEmpty()) {// object.properties
        JsonObject propertiesObject = new JsonObject();
        for (Map.Entry<String, JsonElement> propertyElemement : jsonElement.getAsJsonObject().entrySet()) {
            propertiesObject.add(propertyElemement.getKey(), makeSchemaElement(propertyElemement.getValue(),
                    propertyElemement.getKey(), false, newRequired));
        }
        jsonSchemaObject.add(JsonSchemaKeywords.PROPERTIES.toString(), propertiesObject);
    } else if (jsonElementType.equals(JsonValueTypes.ARRAY.toString())
            && jsonElement.getAsJsonArray().size() > 0) {// array.items
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        jsonSchemaObject.add(JsonSchemaKeywords.ITEMS.toString(),
                makeSchemaElement(jsonArray.get(0), "0", false, new JsonArray()));

    }

    // required && V4
    if (jsonElementType.equals(JsonValueTypes.OBJECT.toString())
            && JsonSchemaVersions.V4.toString().equals(jsonSchemaConfig.getVersion())) {// object.required
        jsonSchemaObject.add(JsonSchemaKeywords.REQUIRED.toString(), newRequired);
    }

    // minitems , uniqueitems
    if (jsonElementType.equals(JsonValueTypes.ARRAY.toString())) {// array
        if (jsonSchemaConfig.isPrintMinItems()) {// array.minitems
            jsonSchemaObject.addProperty(JsonSchemaKeywords.MINITEMS.toString(),
                    jsonSchemaConfig.getMinItems());
        }
        if (jsonSchemaConfig.isPrintUniqueItems()) {// array.uniqueitems
            jsonSchemaObject.addProperty(JsonSchemaKeywords.UNIQUEITEMS.toString(),
                    jsonSchemaConfig.isUniqueItems());
        }
    }

    return jsonSchemaObject;
}

From source file:com.goodow.realtime.server.rpc.PollHandler.java

License:Apache License

private JsonArray fetchDeltas(JsonArray ids, String sessionId)
        throws IOException, SlobNotFoundException, AccessDeniedException {
    JsonArray msgs = new JsonArray();
    SlobStore store = slobFacilities.getSlobStore();
    String token = null;//  w  w w  . j  av  a  2s . c  om
    for (JsonElement elem : ids) {
        JsonArray array = elem.getAsJsonArray();
        ObjectId key = new ObjectId(array.get(0).getAsString());
        long startRev = array.get(1).getAsLong();
        Long endVersion = array.size() >= 3 ? array.get(2).getAsLong() : null;

        ConnectResult r = null;
        try {
            r = store.reconnect(key, new Session(context.get().getAccountInfo().getUserId(), sessionId));
        } catch (SlobNotFoundException e) {
            if (startRev == 1) {
                continue;
            }
            throw e;
        }
        if (r.getChannelToken() != null) {
            assert token == null || token.equals(r.getChannelToken());
            token = r.getChannelToken();
        }
        JsonObject msg = new JsonObject();
        msg.addProperty(Params.ID, key.toString());
        boolean isEmpty = deltaHandler.fetchDeltas(msg, key, startRev - 1, endVersion);
        if (!isEmpty) {
            msgs.add(msg);
        }
    }
    if (token != null) {
        JsonObject tokenMsg = new JsonObject();
        tokenMsg.addProperty(Params.ID, Params.TOKEN);
        tokenMsg.addProperty(Params.TOKEN, token);
        msgs.add(tokenMsg);
    }
    return msgs;
}