Example usage for com.google.gson JsonArray get

List of usage examples for com.google.gson JsonArray get

Introduction

In this page you can find the example usage for com.google.gson JsonArray get.

Prototype

public JsonElement get(int i) 

Source Link

Document

Returns the ith element of the array.

Usage

From source file:com.github.sommeri.sourcemap.SourceMapConsumerV3.java

License:Apache License

private String[] getJavaStringArray(JsonArray array) {
    int len = array.size();
    String[] result = new String[len];
    for (int i = 0; i < len; i++) {
        result[i] = array.get(i).isJsonNull() ? null : array.get(i).getAsString();
    }/*from  w  ww  . ja  v  a 2 s.c  om*/
    return result;
}

From source file:com.github.tarsys.android.orm.dataobjects.JSONDataSource.java

public JSONDataSource(JsonArray jArray) {
    if (jArray != null && jArray.size() > 0) {
        // cogemos el primer objeto del array, para sacarle sus claves...
        try {//from   w  w  w . ja  v  a 2  s. c  o  m
            JsonObject obj = jArray.get(0).getAsJsonObject();
            if (obj != null) {
                for (Map.Entry<String, JsonElement> e : obj.entrySet())
                    this.columns.add(e.getKey());
            }
            this.jsonData = jArray.toString();
        } catch (Exception ex) {
        }
    }
}

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  www. ja 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  ww . 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 /*  w w w . java 2  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.goforer.beatery.ui.fragment.EateryInfoFragment.java

License:Apache License

@Subscribe(threadMode = ThreadMode.ASYNC)
public void onEvent(EateryInfoEvent event) {
    if (event.getEateryId() == mItems.get(mItemPosition).getId()) {
        if (event.getResponseClient() != null && event.getResponseClient().isSuccessful()) {
            JsonArray jsonArray = event.getResponseClient().getResponseEntity().getAsJsonArray();
            if (jsonArray.size() > 0) {
                JsonElement element = jsonArray.get(0);
                mEateryInfo = EateryInfo.gson().fromJson(element, EateryInfo.class);
                setEateryInfoChanged(true);
                requestComment(false);//  www  .jav a  2s. c  o m
                EventBus.getDefault().post(new EateryInfoUpdatedAction(mEateryInfo));
            } else {
                infoFetchFail();
            }
        } else {
            infoFetchFail();
        }

        notifyRefreshFinished();
    }
}

From source file:com.goodow.realtime.server.model.DeltaSerializer.java

License:Apache License

public static JsonElement dataToClientJson(Delta<String> data, long resultingRevision) {
    Preconditions.checkArgument(resultingRevision <= MAX_DOUBLE_INTEGER, "Resulting revision %s is too large",
            resultingRevision);/*from   w  w  w  .  j av a  2 s  . co m*/

    // Assume payload is JSON, and parse it to avoid nested json.
    // TODO: Consider using Delta<JSONObject> instead.
    // The reason I haven't done it yet is because it's not immutable,
    // and also for reasons described in Delta.
    JsonElement payloadJson;
    try {
        payloadJson = new JsonParser().parse(data.getPayload());
    } catch (JsonParseException e) {
        throw new IllegalArgumentException("Invalid payload for " + data, e);
    }

    JsonArray json = new JsonArray();
    try {
        Preconditions.checkArgument(resultingRevision >= 0, "invalid rev %s", resultingRevision);
        json.add(new JsonPrimitive(resultingRevision));
        long sanityCheck = json.get(0).getAsLong();
        if (sanityCheck != resultingRevision) {
            throw new AssertionError("resultingRevision " + resultingRevision
                    + " not losslessly represented in JSON, got back " + sanityCheck);
        }
        json.add(new JsonPrimitive(data.getSession().userId));
        json.add(new JsonPrimitive(data.getSession().sessionId));
        json.add(payloadJson);
        return json;
    } catch (JsonParseException e) {
        throw new Error(e);
    }
}

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;//from w w  w.  j  ava 2 s .  co  m
    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;
}

From source file:com.google.api.ads.adwords.awalerting.sampleimpl.rule.ConvertMoneyValue.java

License:Open Source License

public ConvertMoneyValue(JsonObject config) {
    if (config.has(MONEY_FIELD_TAG) && config.has(MONEY_FIELDS_TAG)) {
        String errorMsg = String.format(
                "Error in ConvertMoneyValue constructor: cannot have both \"%s\" and \"%s\" in config.",
                MONEY_FIELD_TAG, MONEY_FIELDS_TAG);
        throw new IllegalArgumentException(errorMsg);
    }// w  w  w  .  j  a v a  2s .  c o m

    moneyFields = new HashSet<String>();
    if (config.has(MONEY_FIELD_TAG)) {
        moneyFields.add(config.get(MONEY_FIELD_TAG).getAsString());
    } else if (config.has(MONEY_FIELDS_TAG)) {
        JsonArray array = config.get(MONEY_FIELDS_TAG).getAsJsonArray();
        for (int i = 0; i < array.size(); i++) {
            moneyFields.add(array.get(i).getAsString());
        }
    } else {
        // Use default
        moneyFields.add(DEFAULT_MONEY_FIELD);
    }
}

From source file:com.google.appinventor.components.runtime.Survey.java

License:Open Source License

/**
 * Creates a new Survey component./*from   www .j  a  v  a 2  s . c o m*/
 * 
 * @param container
 *            container the component will be placed in
 * @throws IOException 
 */
public Survey(ComponentContainer container) throws IOException {
    super(container);
    mainUI = container.$form();
    exportRoot = new java.io.File(Environment.getExternalStorageDirectory(), mainUI.getPackageName())
            + java.io.File.separator + "export";

    JsonParser parse = new JsonParser();
    webview = new WebView(container.$context());
    webview.getSettings().setJavaScriptEnabled(true);
    webview.setFocusable(true);
    webview.setVerticalScrollBarEnabled(true);

    container.$add(this);

    webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus()) {
                    v.requestFocus();
                }
                break;
            }
            return false;
        }
    });

    // set the initial default properties. Height and Width
    // will be fill-parent, which will be the default for the web viewer.

    Width(LENGTH_FILL_PARENT);
    Height(LENGTH_FILL_PARENT);

    //set default survey style
    style = TEXTBOX; //default style

    // see if the Survey is created by someone tapping on a notification! 
    // create the Survey and load it in the webviewer
    /* e.g. 
     * value = {
     * "style": "multipleChoice", 
     * "question": "What is your favorite food"
     * "options": ["apple", "banana", "strawberry", "orange"],
     * "surveyGroup": "MIT-food-survey"
     * }
     * 
     */
    initValues = container.$form().getSurveyStartValues();
    Log.i(TAG, "startVal Suvey:" + initValues.toString());
    if (initValues != "") {

        JsonObject values = (JsonObject) parse.parse(initValues);
        this.style = values.get("style").getAsString();
        this.question = values.get("question").getAsString();
        this.surveyGroup = values.get("surveyGroup").getAsString();
        ArrayList<String> arrOptions = new ArrayList<String>();
        JsonArray _options = values.get("options").getAsJsonArray();
        for (int i = 0; i < _options.size(); i++) {
            arrOptions.add(_options.get(i).getAsString());
        }

        this.options = arrOptions;
        this.styleFromIntent = values.get("style").getAsString();
        Log.i(TAG, "Survey component got created");
    }

}