com.google.gson.JsonPrimitive

Here are the examples of the java api com.google.gson.JsonPrimitive taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

201 Examples 7

19 Source : GetAdsResponse.java
with MIT License
from VKCOM

public GetAdsResponse setAdPlatform(JsonPrimitive adPlatform) {
    this.adPlatform = adPlatform;
    return this;
}

19 Source : GetAdsLayoutResponse.java
with MIT License
from VKCOM

public GetAdsLayoutResponse setPreviewLink(JsonPrimitive previewLink) {
    this.previewLink = previewLink;
    return this;
}

19 Source : AdLayout.java
with MIT License
from VKCOM

public AdLayout setPreviewLink(JsonPrimitive previewLink) {
    this.previewLink = previewLink;
    return this;
}

19 Source : Ad.java
with MIT License
from VKCOM

public Ad setAdPlatform(JsonPrimitive adPlatform) {
    this.adPlatform = adPlatform;
    return this;
}

19 Source : FeatureTransformer.java
with MIT License
from TerraForged

private JsonPrimitive transformValue(JsonPrimitive primitive, Context context) {
    JsonPrimitive result = valueTransformers.get(primitive);
    if (result != null) {
        context.add(primitive);
        return result;
    }
    return primitive;
}

19 Source : Search.java
with MIT License
from TerraForged

public boolean test(JsonPrimitive value) {
    boolean hasMatch = false;
    for (Matcher matcher : matchers) {
        hasMatch |= matcher.test(value);
    }
    return hasMatch;
}

19 Source : Matcher.java
with MIT License
from TerraForged

public boolean test(JsonPrimitive value) {
    return set.remove(value);
}

19 Source : JsonUtils.java
with Apache License 2.0
from pingcap

public clreplaced JsonUtils {

    private static final int KEY_ENTRY_LENGTH = 6;

    private static final int VALUE_ENTRY_SIZE = 5;

    // TypeCodeObject indicates the JSON is an object.
    private static final byte TYPE_CODE_OBJECT = 0x01;

    // TypeCodeArray indicates the JSON is an array.
    private static final byte TYPE_CODE_ARRAY = 0x03;

    // TypeCodeLiteral indicates the JSON is a literal.
    private static final byte TYPE_CODE_LITERAL = 0x04;

    // TypeCodeInt64 indicates the JSON is a signed integer.
    private static final byte TYPE_CODE_INT64 = 0x09;

    // TypeCodeUint64 indicates the JSON is a unsigned integer.
    private static final byte TYPE_CODE_UINT64 = 0x0a;

    // TypeCodeFloat64 indicates the JSON is a double float number.
    private static final byte TYPE_CODE_FLOAT64 = 0x0b;

    // TypeCodeString indicates the JSON is a string.
    private static final byte TYPE_CODE_STRING = 0x0c;

    // LiteralNil represents JSON null.
    private static final byte LITERAL_NIL = 0x00;

    // LiteralTrue represents JSON true.
    private static final byte LITERAL_TRUE = 0x01;

    // LiteralFalse represents JSON false.
    private static final byte LITERAL_FALSE = 0x02;

    private static final JsonPrimitive JSON_FALSE = new JsonPrimitive(false);

    private static final JsonPrimitive JSON_TRUE = new JsonPrimitive(true);

    public static JsonElement parseJson(DataInput di) {
        return parseValue(readByte(di), di);
    }

    /**
     * The binary JSON format from MySQL 5.7 is as follows:
     *
     * <pre>{@code
     * JsonFormat {
     *      JSON doc ::= type value
     *      type ::=
     *          0x01 |       // large JSON object
     *          0x03 |       // large JSON array
     *          0x04 |       // literal (true/false/null)
     *          0x05 |       // int16
     *          0x06 |       // uint16
     *          0x07 |       // int32
     *          0x08 |       // uint32
     *          0x09 |       // int64
     *          0x0a |       // uint64
     *          0x0b |       // double
     *          0x0c |       // utf8mb4 string
     *      value ::=
     *          object  |
     *          array   |
     *          literal |
     *          number  |
     *          string  |
     *      object ::= element-count size key-entry* value-entry* key* value*
     *      array ::= element-count size value-entry* value*
     *      // number of members in object or number of elements in array
     *      element-count ::= uint32
     *      // number of bytes in the binary representation of the object or array
     *      size ::= uint32
     *      key-entry ::= key-offset key-length
     *      key-offset ::= uint32
     *      key-length ::= uint16    // key length must be less than 64KB
     *      value-entry ::= type offset-or-inlined-value
     *      // This field holds either the offset to where the value is stored,
     *      // or the value itself if it is small enough to be inlined (that is,
     *      // if it is a JSON literal or a small enough [u]int).
     *      offset-or-inlined-value ::= uint32
     *      key ::= utf8mb4-data
     *      literal ::=
     *          0x00 |   // JSON null literal
     *          0x01 |   // JSON true literal
     *          0x02 |   // JSON false literal
     *      number ::=  ....    // little-endian format for [u]int(16|32|64), whereas
     *                          // double is stored in a platform-independent, eight-byte
     *                          // format using float8store()
     *      string ::= data-length utf8mb4-data
     *      data-length ::= uint8*    // If the high bit of a byte is 1, the length
     *                                // field is continued in the next byte,
     *                                // otherwise it is the last byte of the length
     *                                // field. So we need 1 byte to represent
     *                                // lengths up to 127, 2 bytes to represent
     *                                // lengths up to 16383, and so on...
     * }
     * }</pre>
     *
     * @param type type byte
     * @param di codec data input
     * @return Json element parsed
     */
    private static JsonElement parseValue(byte type, DataInput di) {
        switch(type) {
            case TYPE_CODE_OBJECT:
                return parseObject(di);
            case TYPE_CODE_ARRAY:
                return parseArray(di);
            case TYPE_CODE_LITERAL:
                return parseLiteralJson(di);
            case TYPE_CODE_INT64:
                return new JsonPrimitive(parseInt64(di));
            case TYPE_CODE_UINT64:
                return new JsonPrimitive(parseUint64(di));
            case TYPE_CODE_FLOAT64:
                return new JsonPrimitive(parseDouble(di));
            case TYPE_CODE_STRING:
                long length = parseDataLength(di);
                return new JsonPrimitive(parseString(di, length));
            default:
                throw new replacedertionError("error type|type=" + (int) type);
        }
    }

    // * notice use this as a unsigned long
    private static long parseUint64(DataInput cdi) {
        byte[] readBuffer = new byte[8];
        readFully(cdi, readBuffer, 0, 8);
        return ((long) (readBuffer[7]) << 56) + ((long) (readBuffer[6] & 255) << 48) + ((long) (readBuffer[5] & 255) << 40) + ((long) (readBuffer[4] & 255) << 32) + ((long) (readBuffer[3] & 255) << 24) + ((readBuffer[2] & 255) << 16) + ((readBuffer[1] & 255) << 8) + ((readBuffer[0] & 255));
    }

    private static void readFully(DataInput di, byte[] buffer) {
        try {
            di.readFully(buffer);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private static void readFully(DataInput cdi, byte[] readBuffer, final int off, final int len) {
        try {
            cdi.readFully(readBuffer, off, len);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private static long parseInt64(DataInput cdi) {
        byte[] readBuffer = new byte[8];
        readFully(cdi, readBuffer);
        return bytesToLong(readBuffer);
    }

    private static long parseUint32(DataInput cdi) {
        byte[] readBuffer = new byte[4];
        readFully(cdi, readBuffer);
        return ((long) (readBuffer[3] & 255) << 24) + ((readBuffer[2] & 255) << 16) + ((readBuffer[1] & 255) << 8) + ((readBuffer[0] & 255));
    }

    private static long bytesToLong(byte[] readBuffer) {
        return ((long) readBuffer[7] << 56) + ((long) (readBuffer[6] & 255) << 48) + ((long) (readBuffer[5] & 255) << 40) + ((long) (readBuffer[4] & 255) << 32) + ((long) (readBuffer[3] & 255) << 24) + ((readBuffer[2] & 255) << 16) + ((readBuffer[1] & 255) << 8) + ((readBuffer[0] & 255));
    }

    private static double parseDouble(DataInput cdi) {
        byte[] readBuffer = new byte[8];
        readFully(cdi, readBuffer);
        return Double.longBitsToDouble(bytesToLong(readBuffer));
    }

    private static int parseUint16(DataInput cdi) {
        byte[] readBuffer = new byte[2];
        readFully(cdi, readBuffer);
        return ((readBuffer[1] & 255) << 8) + ((readBuffer[0] & 255));
    }

    private static String parseString(DataInput di, long length) {
        byte[] buffer = new byte[Math.toIntExact(length)];
        readFully(di, buffer);
        return new String(buffer, StandardCharsets.UTF_8);
    }

    /**
     * @param di data input
     * @return length of data.
     */
    private static long parseDataLength(DataInput di) {
        long x = 0;
        byte b;
        int i = 0;
        int s = 0;
        while ((b = readByte(di)) < 0) {
            if (i == 9) {
                throw new IllegalArgumentException("overflow: found >=9 leading bytes");
            }
            x |= ((long) (b & 0x7f)) << s;
            s += 7;
            i++;
        }
        if (i == 9 && b > 1) {
            throw new IllegalArgumentException("overflow: 8 leading byte and last one > 1");
        }
        x |= ((long) b) << s;
        return x;
    }

    @Nullable
    private static Boolean parseLiteral(DataInput cdi) {
        byte type;
        type = readByte(cdi);
        switch(type) {
            case LITERAL_FALSE:
                return Boolean.FALSE;
            case LITERAL_NIL:
                return null;
            case LITERAL_TRUE:
                return Boolean.TRUE;
            default:
                throw new replacedertionError("unknown literal type|" + (int) type);
        }
    }

    private static byte readByte(DataInput cdi) {
        byte type;
        try {
            type = cdi.readByte();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
        return type;
    }

    private static JsonArray parseArray(DataInput di) {
        long elementCount = parseUint32(di);
        long size = parseUint32(di);
        byte[] buffer = new byte[Math.toIntExact(size - 8)];
        readFully(di, buffer);
        JsonArray jsonArray = new JsonArray();
        for (int i = 0; i < elementCount; i++) {
            JsonElement value = parseValueEntry(buffer, VALUE_ENTRY_SIZE * i);
            jsonArray.add(value);
        }
        return jsonArray;
    }

    private static JsonObject parseObject(DataInput di) {
        long elementCount = parseUint32(di);
        long size = parseUint32(di);
        byte[] buffer = new byte[Math.toIntExact(size - 8)];
        readFully(di, buffer);
        JsonObject jsonObject = new JsonObject();
        for (int i = 0; i < elementCount; i++) {
            KeyEntry keyEntry = parseKeyEntry(ByteStreams.newDataInput(buffer, i * KEY_ENTRY_LENGTH));
            String key = parseString(ByteStreams.newDataInput(buffer, Math.toIntExact(keyEntry.keyOffset - 8)), keyEntry.keyLength);
            long valueEntryOffset = elementCount * KEY_ENTRY_LENGTH + i * VALUE_ENTRY_SIZE;
            JsonElement value = parseValueEntry(buffer, valueEntryOffset);
            jsonObject.add(key, value);
        }
        return jsonObject;
    }

    private static JsonElement parseValueEntry(byte[] buffer, long valueEntryOffset) {
        byte valueType = buffer[Math.toIntExact(valueEntryOffset)];
        JsonElement value;
        ByteArrayDataInput bs = ByteStreams.newDataInput(buffer, Math.toIntExact(valueEntryOffset + 1));
        switch(valueType) {
            case TYPE_CODE_LITERAL:
                value = parseLiteralJson(bs);
                break;
            default:
                long valueOffset = parseUint32(bs);
                value = parseValue(valueType, ByteStreams.newDataInput(buffer, Math.toIntExact(valueOffset - 8)));
        }
        return value;
    }

    private static JsonElement parseLiteralJson(DataInput di) {
        JsonElement value;
        Boolean bool = parseLiteral(di);
        if (bool == null) {
            value = JsonNull.INSTANCE;
        } else if (bool) {
            value = JSON_TRUE;
        } else {
            value = JSON_FALSE;
        }
        return value;
    }

    private static KeyEntry parseKeyEntry(DataInput di) {
        return new KeyEntry(parseUint32(di), parseUint16(di));
    }

    static clreplaced KeyEntry {

        long keyOffset;

        int keyLength;

        KeyEntry(long keyOffset, int keyLength) {
            this.keyOffset = keyOffset;
            this.keyLength = keyLength;
        }
    }
}

19 Source : JWT.java
with Eclipse Public License 1.0
from OpenLiberty

protected JsonArray handleList(List<String> strlist) {
    JsonArray list = null;
    if (strlist != null) {
        list = new JsonArray();
        for (String str : strlist) {
            JsonPrimitive jsonPrimitiveObj = new JsonPrimitive(str);
            list.add(jsonPrimitiveObj);
        }
    }
    return list;
}

19 Source : JsonTokenUtil.java
with Eclipse Public License 1.0
from OpenLiberty

static Number getJsonPrimitiveNumber(JsonPrimitive primitive) {
    long longVal = primitive.getAsLong();
    double doubleVal = primitive.getAsDouble();
    if (longVal < doubleVal) {
        // The long value must have been rounded/truncated, so the "true" value should be a double
        return doubleVal;
    }
    return longVal;
}

19 Source : BetterJsonObject.java
with GNU Lesser General Public License v3.0
from HyperiumClient

/**
 * The optional string method, returns the default value if
 * the key is null, empty or the data does not contain
 * the key. This will also return the default value if
 * the data value is not a string
 *
 * @param key the key the value will be loaded from
 * @return the value in the json data set or the default if the key cannot be found
 */
public String optString(String key, String value) {
    if (key == null || key.isEmpty() || !has(key))
        return value;
    JsonPrimitive primitive = asPrimitive(get(key));
    return primitive != null && primitive.isString() ? primitive.getreplacedtring() : value;
}

19 Source : BetterJsonObject.java
with GNU Lesser General Public License v3.0
from HyperiumClient

/**
 * The optional boolean method, returns the default value if
 * the key is null, empty or the data does not contain
 * the key. This will also return the default value if
 * the data value is not a boolean
 *
 * @param key the key the value will be loaded from
 * @return the value in the json data set or the default if the key cannot be found
 */
public boolean optBoolean(String key, boolean value) {
    if (key == null || key.isEmpty() || !has(key))
        return value;
    JsonPrimitive primitive = asPrimitive(get(key));
    return primitive != null && primitive.isBoolean() ? primitive.getAsBoolean() : value;
}

18 Source : FeatureParser.java
with MIT License
from TerraForged

private static JsonPrimitive keyToPrimitive(String key, JsonPrimitive value) {
    if (value.isString()) {
        return new JsonPrimitive(key);
    }
    if (value.isNumber()) {
        try {
            Double.parseDouble(key);
            return new JsonPrimitive(new JsonPrimitive(key).getAsNumber());
        } catch (NumberFormatException e) {
            return null;
        }
    }
    if (value.isBoolean()) {
        if (key.equalsIgnoreCase("true") || key.equalsIgnoreCase("false")) {
            return new JsonPrimitive(new JsonPrimitive(key).getAsBoolean());
        }
    }
    return null;
}

18 Source : JsonConverter.java
with Apache License 2.0
from osswangxining

private static Consumer<AttributeKvEntry> addToObject(JsonObject result) {
    return de -> {
        JsonPrimitive value;
        switch(de.getDataType()) {
            case BOOLEAN:
                value = new JsonPrimitive(de.getBooleanValue().get());
                break;
            case DOUBLE:
                value = new JsonPrimitive(de.getDoubleValue().get());
                break;
            case LONG:
                value = new JsonPrimitive(de.getLongValue().get());
                break;
            case STRING:
                value = new JsonPrimitive(de.getStrValue().get());
                break;
            default:
                throw new IllegalArgumentException("Unsupported data type: " + de.getDataType());
        }
        result.add(de.getKey(), value);
    };
}

18 Source : JWTToken.java
with Eclipse Public License 1.0
from OpenLiberty

JsonArray handleList(List<String> strlist) {
    // need
    JsonArray list = null;
    // net.oauth.jsontoken-1.1/lib/gson-2.2.4.jar
    if (strlist != null) {
        list = new JsonArray();
        for (String str : strlist) {
            Log.info(thisClreplaced, "handleList", "String entry: " + str);
            JsonPrimitive jsonPrimitiveObj = new JsonPrimitive(str);
            list.add(jsonPrimitiveObj);
        }
    }
    return list;
}

18 Source : JWTToken.java
with Eclipse Public License 1.0
from OpenLiberty

public long getPayloadLong(String key) {
    try {
        JsonPrimitive objLong = _payloadObj.getAsJsonPrimitive(key);
        if (objLong == null) {
            return -1L;
        }
        return objLong.getAsLong();
    } catch (Exception e) {
        return -1L;
    }
}

18 Source : XGsonBuilder.java
with GNU Affero General Public License v3.0
from o2oa

public static String extractString(JsonElement jsonElement, String name) {
    if ((null != jsonElement) && jsonElement.isJsonObject() && StringUtils.isNotEmpty(name)) {
        JsonElement element = extract(jsonElement, name);
        if (null != element && element.isJsonPrimitive()) {
            JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
            if (jsonPrimitive.isString())
                return jsonPrimitive.getreplacedtring();
        }
    }
    return null;
}

18 Source : GlobalPalette.java
with GNU General Public License v3.0
from mircokroon

/**
 * Turns properties hashmap into a compoundtag, which lets us correctly handle the block states that depend on
 * properties.
 */
CompoundTag getProperties() {
    CompoundTag res = new CompoundTag();
    for (Map.Entry<String, JsonPrimitive> entry : properties.entrySet()) {
        JsonPrimitive wrappedVal = entry.getValue();
        SpecificTag value;
        if (wrappedVal.isBoolean()) {
            value = new ByteTag(wrappedVal.getAsBoolean() ? 1 : 0);
        } else if (wrappedVal.isNumber()) {
            value = new IntTag(wrappedVal.getAsInt());
        } else {
            value = new StringTag(wrappedVal.getreplacedtring());
        }
        res.add(entry.getKey(), value);
    }
    return res;
}

18 Source : BetterJsonObject.java
with GNU Lesser General Public License v3.0
from HyperiumClient

/**
 * The optional int method, returns the default value if
 * the key is null, empty or the data does not contain
 * the key. This will also return the default value if
 * the data value is not a number
 *
 * @param key the key the value will be loaded from
 * @return the value in the json data set or the default if the key cannot be found
 */
public int optInt(String key, int value) {
    if (key == null || key.isEmpty() || !has(key))
        return value;
    JsonPrimitive primitive = asPrimitive(get(key));
    try {
        if (primitive != null && primitive.isNumber())
            return primitive.getAsInt();
    } catch (NumberFormatException ignored) {
    }
    return value;
}

18 Source : BetterJsonObject.java
with GNU Lesser General Public License v3.0
from HyperiumClient

/**
 * The optional double method, returns the default value if
 * the key is null, empty or the data does not contain
 * the key. This will also return the default value if
 * the data value is not a number
 *
 * @param key the key the value will be loaded from
 * @return the value in the json data set or the default if the key cannot be found
 */
public double optDouble(String key, double value) {
    if (key == null || key.isEmpty() || !has(key))
        return value;
    JsonPrimitive primitive = asPrimitive(get(key));
    try {
        if (primitive != null && primitive.isNumber())
            return primitive.getAsDouble();
    } catch (NumberFormatException ignored) {
    }
    return value;
}

18 Source : ParseJsonUseGson.java
with Apache License 2.0
from fangjinuo

/**
 * 去掉ValueNode的包装, 直接返回内容 *
 */
private static Object unwrapJsonPrimitive(JsonPrimitive element) {
    // 略坑, 居然没有直接获取value值的public方法
    JsonPrimitive primitive = (JsonPrimitive) element;
    return Reflects.getAnyFieldValue(primitive, "value", true, true);
}

18 Source : DBNode.java
with Apache License 2.0
from didi

/**
 * 根据给定的key从给定的字典数据源里拿String数据
 */
protected boolean getBoolean(String rawKey, JsonObject dict) {
    if (rawKey.startsWith("${") && rawKey.endsWith("}")) {
        String variable = rawKey.substring(2, rawKey.length() - 1);
        String[] keys = variable.split("\\.");
        JsonPrimitive jsonPrimitive;
        if (keys.length == 1) {
            jsonPrimitive = dict.getAsJsonPrimitive(variable);
        } else {
            jsonPrimitive = getNestJsonPrimitive(keys, dict);
        }
        if (null != jsonPrimitive) {
            return jsonPrimitive.getreplacedtring().equals("true");
        }
    }
    return "true".equals(rawKey);
}

18 Source : DBNode.java
with Apache License 2.0
from didi

/**
 * 根据给定的key从data pool里拿int数据
 */
protected int getInt(String rawKey, JsonObject dict) {
    if (rawKey.startsWith("${") && rawKey.endsWith("}")) {
        String variable = rawKey.substring(2, rawKey.length() - 1);
        String[] keys = variable.split("\\.");
        JsonPrimitive jsonPrimitive;
        if (keys.length == 1) {
            jsonPrimitive = dict.getAsJsonPrimitive(variable);
        } else {
            jsonPrimitive = getNestJsonPrimitive(keys, dict.getAsJsonObject(keys[0]));
        }
        if (null != jsonPrimitive) {
            return jsonPrimitive.getAsInt();
        }
    }
    return -1;
}

18 Source : DBNode.java
with Apache License 2.0
from didi

/**
 * 根据给定的key从给定的字典数据源里拿String数据
 */
private String getVariableString(String rawKey, @NonNull JsonObject dict) {
    if (rawKey.startsWith("${") && rawKey.endsWith("}")) {
        String variable = rawKey.substring(2, rawKey.length() - 1);
        String[] keys = variable.split("\\.");
        JsonPrimitive jsonPrimitive;
        if (keys.length == 1) {
            jsonPrimitive = dict.getAsJsonPrimitive(variable);
        } else {
            jsonPrimitive = getNestJsonPrimitive(keys, dict.getAsJsonObject(keys[0]));
        }
        if (jsonPrimitive != null) {
            return jsonPrimitive.getreplacedtring();
        }
    }
    return rawKey;
}

18 Source : SchemaConverter.java
with Apache License 2.0
from data-integrations

private Schema toSchema(String name, JsonPrimitive primitive) throws RecordConvertorException {
    Object value = JsParser.getValue(primitive);
    try {
        return Schema.nullableOf(new SimpleSchemaGenerator().generate(value.getClreplaced()));
    } catch (UnsupportedTypeException e) {
        throw new RecordConvertorException(String.format("Unable to convert field '%s' to basic type.", name), e);
    }
}

18 Source : SimpleMapperTest.java
with Apache License 2.0
from Accenture

@Test
public void typedNumberShouldMapFloat() {
    final JsonPrimitive number = new JsonPrimitive("1.12");
    Object result = SimpleMapper.getInstance().typedNumber(number);
    replacedertThat(result, is(1.12d));
}

18 Source : SimpleMapperTest.java
with Apache License 2.0
from Accenture

@Test
public void typedNumberShouldMapDouble() {
    final JsonPrimitive number = new JsonPrimitive("1.12345678");
    Object result = SimpleMapper.getInstance().typedNumber(number);
    replacedertThat(result, is(1.12345678d));
}

17 Source : EiDASCertificate.java
with Apache License 2.0
from yuriylesyuk

protected JsonArray getKeyUsageToJsonArray(boolean[] kus) {
    JsonArray ja = new JsonArray();
    for (int i = 0; i < kus.length; i++) {
        if (kus[i]) {
            JsonPrimitive kuJsonString = new JsonPrimitive(keyUsagesBitNames.get(i));
            ja.add(kuJsonString);
        }
    }
    return ja;
}

17 Source : GeoSource.java
with Apache License 2.0
from yahoo

@Query
public Place getPlace(@Key("text") String text) throws InterruptedException, ExecutionException, TimeoutException {
    JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL, "q", "select * from geo.places where text='" + text + "'");
    JsonPrimitive jsonObj = jsonObject.getAsJsonObject("query").getAsJsonObject("results").getAsJsonObject("place").getAsJsonPrimitive("woeid");
    return new Place(text, jsonObj.getreplacedtring());
}

17 Source : XGsonBuilder.java
with GNU Affero General Public License v3.0
from o2oa

public static Boolean extractBoolean(JsonElement jsonElement, String name) {
    if ((null != jsonElement) && jsonElement.isJsonObject() && StringUtils.isNotEmpty(name)) {
        JsonElement element = extract(jsonElement, name);
        if (null != element && element.isJsonPrimitive()) {
            JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
            if (jsonPrimitive.isBoolean())
                return jsonPrimitive.getAsBoolean();
        }
    }
    return null;
}

17 Source : UtilitiesXTests.java
with Apache License 2.0
from hapifhir

private static String compareNodes(String path, JsonElement n1, JsonElement n2) {
    if (n1.getClreplaced() != n2.getClreplaced())
        return "properties differ at " + path + ": type " + n1.getClreplaced().getName() + "/" + n2.getClreplaced().getName();
    else if (n1 instanceof JsonPrimitive) {
        JsonPrimitive p1 = (JsonPrimitive) n1;
        JsonPrimitive p2 = (JsonPrimitive) n2;
        if (p1.isBoolean() && p2.isBoolean()) {
            if (p1.getAsBoolean() != p2.getAsBoolean())
                return "boolean property values differ at " + path + ": type " + p1.getreplacedtring() + "/" + p2.getreplacedtring();
        } else if (p1.isString() && p2.isString()) {
            String s1 = p1.getreplacedtring();
            String s2 = p2.getreplacedtring();
            if (!(s1.contains("<div") && s2.contains("<div")))
                if (!s1.equals(s2))
                    if (!sameBytes(unBase64(s1), unBase64(s2)))
                        return "string property values differ at " + path + ": type " + s1 + "/" + s2;
        } else if (p1.isNumber() && p2.isNumber()) {
            if (!p1.getreplacedtring().equals(p2.getreplacedtring()))
                return "number property values differ at " + path + ": type " + p1.getreplacedtring() + "/" + p2.getreplacedtring();
        } else
            return "property types differ at " + path + ": type " + p1.getreplacedtring() + "/" + p2.getreplacedtring();
    } else if (n1 instanceof JsonObject) {
        String s = compareObjects(path, (JsonObject) n1, (JsonObject) n2);
        if (!Utilities.noString(s))
            return s;
    } else if (n1 instanceof JsonArray) {
        JsonArray a1 = (JsonArray) n1;
        JsonArray a2 = (JsonArray) n2;
        if (a1.size() != a2.size())
            return "array properties differ at " + path + ": count " + Integer.toString(a1.size()) + "/" + Integer.toString(a2.size());
        for (int i = 0; i < a1.size(); i++) {
            String s = compareNodes(path + "[" + Integer.toString(i) + "]", a1.get(i), a2.get(i));
            if (!Utilities.noString(s))
                return s;
        }
    } else if (n1 instanceof JsonNull) {
    } else
        return "unhandled property " + n1.getClreplaced().getName();
    return null;
}

17 Source : JsonParser.java
with Apache License 2.0
from hapifhir

private void parseChildPrimitiveInstance(Element context, Property property, String name, String npath, JsonElement main, JsonElement fork) throws FHIRException {
    if (main != null && !(main instanceof JsonPrimitive))
        logError(line(main), col(main), npath, IssueType.INVALID, "This property must be an simple value, not a " + main.getClreplaced().getName(), IssueSeverity.ERROR);
    else if (fork != null && !(fork instanceof JsonObject))
        logError(line(fork), col(fork), npath, IssueType.INVALID, "This property must be an object, not a " + fork.getClreplaced().getName(), IssueSeverity.ERROR);
    else {
        Element n = new Element(name, property).markLocation(line(main != null ? main : fork), col(main != null ? main : fork));
        context.getChildren().add(n);
        if (main != null) {
            JsonPrimitive p = (JsonPrimitive) main;
            n.setValue(p.getreplacedtring());
            if (!n.getProperty().isChoice() && n.getType().equals("xhtml")) {
                try {
                    n.setXhtml(new XhtmlParser().setValidatorMode(policy == ValidationPolicy.EVERYTHING).parse(n.getValue(), null).getDoreplacedentElement());
                } catch (Exception e) {
                    logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing XHTML: " + e.getMessage(), IssueSeverity.ERROR);
                }
            }
            if (policy == ValidationPolicy.EVERYTHING) {
                // now we cross-check the primitive format against the stated type
                if (Utilities.existsInList(n.getType(), "boolean")) {
                    if (!p.isBoolean())
                        logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a boolean", IssueSeverity.ERROR);
                } else if (Utilities.existsInList(n.getType(), "integer", "unsignedInt", "positiveInt", "decimal")) {
                    if (!p.isNumber())
                        logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a number", IssueSeverity.ERROR);
                } else if (!p.isString())
                    logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a string", IssueSeverity.ERROR);
            }
        }
        if (fork != null) {
            JsonObject child = (JsonObject) fork;
            checkObject(child, npath);
            parseChildren(npath, child, n, false);
        }
    }
}

17 Source : TestingUtilities.java
with Apache License 2.0
from hapifhir

private static String compareNodes(String path, JsonElement n1, JsonElement n2) {
    if (n1.getClreplaced() != n2.getClreplaced())
        return "properties differ at " + path + ": type " + n1.getClreplaced().getName() + "/" + n2.getClreplaced().getName();
    else if (n1 instanceof JsonPrimitive) {
        JsonPrimitive p1 = (JsonPrimitive) n1;
        JsonPrimitive p2 = (JsonPrimitive) n2;
        if (p1.isBoolean() && p2.isBoolean()) {
            if (p1.getAsBoolean() != p2.getAsBoolean())
                return "boolean property values differ at " + path + ": type " + p1.getreplacedtring() + "/" + p2.getreplacedtring();
        } else if (p1.isString() && p2.isString()) {
            String s1 = p1.getreplacedtring();
            String s2 = p2.getreplacedtring();
            if (!(s1.contains("<div") && s2.contains("<div")))
                if (!s1.equals(s2))
                    if (!sameBytes(unBase64(s1), unBase64(s2)))
                        return "string property values differ at " + path + ": type " + s1 + "/" + s2;
        } else if (p1.isNumber() && p2.isNumber()) {
            if (!p1.getreplacedtring().equals(p2.getreplacedtring()))
                return "number property values differ at " + path + ": type " + p1.getreplacedtring() + "/" + p2.getreplacedtring();
        } else
            return "property types differ at " + path + ": type " + p1.getreplacedtring() + "/" + p2.getreplacedtring();
    } else if (n1 instanceof JsonObject) {
        String s = compareObjects(path, (JsonObject) n1, (JsonObject) n2);
        if (!Utilities.noString(s))
            return s;
    } else if (n1 instanceof JsonArray) {
        JsonArray a1 = (JsonArray) n1;
        JsonArray a2 = (JsonArray) n2;
        if (a1.size() != a1.size())
            return "array properties differ at " + path + ": count " + Integer.toString(a1.size()) + "/" + Integer.toString(a2.size());
        for (int i = 0; i < a1.size(); i++) {
            String s = compareNodes(path + "[" + Integer.toString(i) + "]", a1.get(i), a2.get(i));
            if (!Utilities.noString(s))
                return s;
        }
    } else if (n1 instanceof JsonNull) {
    } else
        return "unhandled property " + n1.getClreplaced().getName();
    return null;
}

17 Source : JsonParser.java
with Apache License 2.0
from hapifhir

private void parseChildPrimitiveInstance(Element context, Property property, String name, String npath, JsonElement main, JsonElement fork) throws FHIRFormatError, DefinitionException {
    if (main != null && !(main instanceof JsonPrimitive))
        logError(line(main), col(main), npath, IssueType.INVALID, "This property must be an simple value, not a " + main.getClreplaced().getName(), IssueSeverity.ERROR);
    else if (fork != null && !(fork instanceof JsonObject))
        logError(line(fork), col(fork), npath, IssueType.INVALID, "This property must be an object, not a " + fork.getClreplaced().getName(), IssueSeverity.ERROR);
    else {
        Element n = new Element(name, property).markLocation(line(main != null ? main : fork), col(main != null ? main : fork));
        context.getChildren().add(n);
        if (main != null) {
            JsonPrimitive p = (JsonPrimitive) main;
            n.setValue(p.getreplacedtring());
            if (!n.getProperty().isChoice() && n.getType().equals("xhtml")) {
                try {
                    n.setXhtml(new XhtmlParser().setValidatorMode(policy == ValidationPolicy.EVERYTHING).parse(n.getValue(), null).getDoreplacedentElement());
                } catch (Exception e) {
                    logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing XHTML: " + e.getMessage(), IssueSeverity.ERROR);
                }
            }
            if (policy == ValidationPolicy.EVERYTHING) {
                // now we cross-check the primitive format against the stated type
                if (Utilities.existsInList(n.getType(), "boolean")) {
                    if (!p.isBoolean())
                        logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a boolean", IssueSeverity.ERROR);
                } else if (Utilities.existsInList(n.getType(), "integer", "unsignedInt", "positiveInt", "decimal")) {
                    if (!p.isNumber())
                        logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a number", IssueSeverity.ERROR);
                } else if (!p.isString())
                    logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a string", IssueSeverity.ERROR);
            }
        }
        if (fork != null) {
            JsonObject child = (JsonObject) fork;
            checkObject(child, npath);
            parseChildren(npath, child, n, false);
        }
    }
}

17 Source : GoogleServicesTask.java
with Apache License 2.0
from google

/**
 * Handle project_info/project_number for @string/gcm_defaultSenderId, and fill the res map with
 * the read value.
 *
 * @param rootObject the root Json object.
 * @throws IOException
 */
private void handleProjectNumberAndProjectId(JsonObject rootObject, Map<String, String> resValues) throws IOException {
    JsonObject projectInfo = rootObject.getAsJsonObject("project_info");
    if (projectInfo == null) {
        throw new GradleException("Missing project_info object");
    }
    JsonPrimitive projectNumber = projectInfo.getAsJsonPrimitive("project_number");
    if (projectNumber == null) {
        throw new GradleException("Missing project_info/project_number object");
    }
    resValues.put("gcm_defaultSenderId", projectNumber.getreplacedtring());
    JsonPrimitive projectId = projectInfo.getAsJsonPrimitive("project_id");
    if (projectId == null) {
        throw new GradleException("Missing project_info/project_id object");
    }
    resValues.put("project_id", projectId.getreplacedtring());
    JsonPrimitive bucketName = projectInfo.getAsJsonPrimitive("storage_bucket");
    if (bucketName != null) {
        resValues.put("google_storage_bucket", bucketName.getreplacedtring());
    }
}

17 Source : GoogleServicesTask.java
with Apache License 2.0
from google

/**
 * Handle a client object for Google App Id.
 */
private void handleGoogleAppId(JsonObject clientObject, Map<String, String> resValues) throws IOException {
    JsonObject clientInfo = clientObject.getAsJsonObject("client_info");
    if (clientInfo == null) {
        // Should not happen
        throw new GradleException("Client does not have client info");
    }
    JsonPrimitive googleAppId = clientInfo.getAsJsonPrimitive("mobilesdk_app_id");
    String googleAppIdStr = googleAppId == null ? null : googleAppId.getreplacedtring();
    if (Strings.isNullOrEmpty(googleAppIdStr)) {
        throw new GradleException("Missing Google App Id. " + "Please follow instructions on https://firebase.google.com/ to get a valid " + "config file that contains a Google App Id");
    }
    resValues.put("google_app_id", googleAppIdStr);
}

17 Source : GoogleServicesTask.java
with Apache License 2.0
from google

private void handleFirebaseUrl(JsonObject rootObject, Map<String, String> resValues) throws IOException {
    JsonObject projectInfo = rootObject.getAsJsonObject("project_info");
    if (projectInfo == null) {
        throw new GradleException("Missing project_info object");
    }
    JsonPrimitive firebaseUrl = projectInfo.getAsJsonPrimitive("firebase_url");
    if (firebaseUrl != null) {
        resValues.put("firebase_database_url", firebaseUrl.getreplacedtring());
    }
}

17 Source : GoogleServicesTask.java
with Apache License 2.0
from google

/**
 * Finds a service by name in the client object. Returns null if the service is not found or if
 * the service is disabled.
 *
 * @param clientObject the json object that represents the client.
 * @param serviceName the service name
 * @return the service if found.
 */
private JsonObject getServiceByName(JsonObject clientObject, String serviceName) {
    JsonObject services = clientObject.getAsJsonObject("services");
    if (services == null)
        return null;
    JsonObject service = services.getAsJsonObject(serviceName);
    if (service == null)
        return null;
    JsonPrimitive status = service.getAsJsonPrimitive("status");
    if (status == null)
        return null;
    String statusStr = status.getreplacedtring();
    if (STATUS_DISABLED.equals(statusStr))
        return null;
    if (!STATUS_ENABLED.equals(statusStr)) {
        getLogger().warn(String.format("Status with value '%1$s' for service '%2$s' is unknown", statusStr, serviceName));
        return null;
    }
    return service;
}

17 Source : ValueDescriptor.java
with GNU General Public License v3.0
from dlanza1

private Value toValue(JsonPrimitive primitive) {
    if (type.equals(Type.AUTO)) {
        if (primitive.isNumber())
            return new FloatValue(primitive.getAsFloat());
        else if (primitive.isBoolean())
            return new BooleanValue(primitive.getAsBoolean());
        else
            return new StringValue(primitive.getreplacedtring());
    }
    return toValue(primitive.getreplacedtring());
}

17 Source : JsonUtil.java
with Apache License 2.0
from didi

public static <T> ArrayList<T> jsonToList(String json, Clreplaced<T> clreplacedOfT) {
    ArrayList<T> listOfT = new ArrayList<>();
    Type type;
    if (clreplacedOfT.isPrimitive()) {
        type = new TypeToken<ArrayList<JsonPrimitive>>() {
        }.getType();
        ArrayList<JsonPrimitive> jsonObjs = gson.fromJson(json, type);
        for (JsonPrimitive jsonObj : jsonObjs) {
            listOfT.add(gson.fromJson(jsonObj, clreplacedOfT));
        }
    } else {
        type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjs = gson.fromJson(json, type);
        for (JsonObject jsonObj : jsonObjs) {
            listOfT.add(gson.fromJson(jsonObj, clreplacedOfT));
        }
    }
    return listOfT;
}

17 Source : SwitchFromSharedKernelToPartnershipCommand.java
with Apache License 2.0
from ContextMapper

@Override
protected SemanticCMLRefactoring getRefactoring(ExecuteCommandParams params) {
    JsonPrimitive participant1 = (JsonPrimitive) params.getArguments().get(1);
    JsonPrimitive participant2 = (JsonPrimitive) params.getArguments().get(2);
    return new SwitchFromSharedKernelToPartnershipRefactoring(participant1.getreplacedtring(), participant2.getreplacedtring());
}

17 Source : SwitchFromPartnershipToSharedKernelCommand.java
with Apache License 2.0
from ContextMapper

@Override
protected SemanticCMLRefactoring getRefactoring(ExecuteCommandParams params) {
    JsonPrimitive participant1 = (JsonPrimitive) params.getArguments().get(1);
    JsonPrimitive participant2 = (JsonPrimitive) params.getArguments().get(2);
    return new SwitchFromPartnershipToSharedKernelRefactoring(participant1.getreplacedtring(), participant2.getreplacedtring());
}

17 Source : SplitBoundedContextByOwnerRefactoringCommand.java
with Apache License 2.0
from ContextMapper

@Override
protected SemanticCMLRefactoring getRefactoring(ExecuteCommandParams params) {
    JsonPrimitive boundedContextName = (JsonPrimitive) params.getArguments().get(1);
    return new SplitBoundedContextByOwner(boundedContextName.getreplacedtring());
}

17 Source : SplitBoundedContextByFeaturesRefactoringCommand.java
with Apache License 2.0
from ContextMapper

@Override
protected SemanticCMLRefactoring getRefactoring(ExecuteCommandParams params) {
    JsonPrimitive boundedContextName = (JsonPrimitive) params.getArguments().get(1);
    return new SplitBoundedContextByFeatures(boundedContextName.getreplacedtring());
}

17 Source : SplitAggregateByEntitiesRefactoringCommand.java
with Apache License 2.0
from ContextMapper

@Override
protected SemanticCMLRefactoring getRefactoring(ExecuteCommandParams params) {
    JsonPrimitive aggregateName = (JsonPrimitive) params.getArguments().get(1);
    return new SplitAggregateByEnreplacediesRefactoring(aggregateName.getreplacedtring());
}

17 Source : ExtractSharedKernelCommand.java
with Apache License 2.0
from ContextMapper

@Override
protected SemanticCMLRefactoring getRefactoring(ExecuteCommandParams params) {
    JsonPrimitive participant1 = (JsonPrimitive) params.getArguments().get(1);
    JsonPrimitive participant2 = (JsonPrimitive) params.getArguments().get(2);
    return new ExtractSharedKernelRefactoring(participant1.getreplacedtring(), participant2.getreplacedtring());
}

17 Source : FeatureFileExecutor.java
with Apache License 2.0
from andrewjc

private void translateScenarioArguments(List<Object> parameters) {
    // TODO: Lookup and replace the list of parameters
    // with data from the test data file
    if (testData != null) {
        for (int i = 0; i < parameters.size(); i++) {
            if (parameters.get(i) instanceof String) {
                String raw = (String) parameters.get(i);
                if (raw.startsWith("$(") && raw.endsWith(")")) {
                    raw = raw.substring("$(".length(), raw.length() - ")".length());
                    String[] pathElements = raw.split("\\.");
                    if (pathElements != null && pathElements.length > 0) {
                        JsonElement elemPointer = testData;
                        for (String element : pathElements) {
                            if (elemPointer.isJsonObject() && elemPointer.getAsJsonObject().has(element)) {
                                elemPointer = elemPointer.getAsJsonObject().get(element);
                                continue;
                            } else {
                                elemPointer = null;
                                break;
                            }
                        }
                        if (elemPointer != null && elemPointer.isJsonPrimitive()) {
                            JsonPrimitive primitive = elemPointer.getAsJsonPrimitive();
                            if (primitive.isString() || primitive.isNumber())
                                parameters.set(i, primitive.getreplacedtring());
                            else if (primitive.isBoolean())
                                parameters.set(i, primitive.getAsBoolean());
                        }
                    }
                }
            }
        }
    }
}

16 Source : SliderSetting.java
with Mozilla Public License 2.0
from Wurst-Imperium

@Override
public final void fromJson(JsonElement json) {
    if (!json.isJsonPrimitive())
        return;
    JsonPrimitive primitive = json.getAsJsonPrimitive();
    if (!primitive.isNumber())
        return;
    double value = primitive.getAsDouble();
    if (value > maximum || value < minimum)
        return;
    value = (int) (value / increment) * increment;
    value = WMath.clamp(value, usableMin, usableMax);
    this.value = value;
    update();
}

16 Source : ModeSetting.java
with Mozilla Public License 2.0
from Wurst-Imperium

@Override
public final void fromJson(JsonElement json) {
    if (!json.isJsonPrimitive())
        return;
    JsonPrimitive primitive = json.getAsJsonPrimitive();
    if (!primitive.isNumber())
        return;
    int selected = primitive.getAsInt();
    if (selected < 0 || selected > modes.length - 1)
        return;
    this.selected = selected;
    if (buttons != null)
        for (int i = 0; i < buttons.length; i++) buttons[i].color = i == selected ? new Color(0x00ff00) : new Color(0x404040);
    update();
}

16 Source : CheckboxSetting.java
with Mozilla Public License 2.0
from Wurst-Imperium

@Override
public final void fromJson(JsonElement json) {
    if (!json.isJsonPrimitive())
        return;
    JsonPrimitive primitive = json.getAsJsonPrimitive();
    if (!primitive.isBoolean())
        return;
    checked = primitive.getAsBoolean();
    update();
}

See More Examples