Java Code Examples for com.google.gson.JsonElement#getAsJsonPrimitive()

The following examples show how to use com.google.gson.JsonElement#getAsJsonPrimitive() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VectorColumnFiller.java    From secor with Apache License 2.0 6 votes vote down vote up
public void convert(JsonElement value, ColumnVector vect, int row) {
    if (value == null || value.isJsonNull()) {
        vect.noNulls = false;
        vect.isNull[row] = true;
    } else if (value.isJsonPrimitive()) {
        UnionColumnVector vector = (UnionColumnVector) vect;
        JsonPrimitive primitive = value.getAsJsonPrimitive();

        JsonType jsonType = getJsonType(primitive);
        ConverterInfo converterInfo = childConverters.get(jsonType);
        if (converterInfo == null) {
            String message = String.format("Unable to infer type for '%s'", primitive);
            throw new IllegalArgumentException(message);
        }

        int vectorIndex = converterInfo.getVectorIndex();
        JsonConverter converter = converterInfo.getConverter();
        vector.tags[row] = vectorIndex;
        converter.convert(value, vector.fields[vectorIndex], row);
    } else {
        // It would be great to support non-primitive types in union type.
        // Let's leave this for another PR in the future.
        throw new UnsupportedOperationException();
    }
}
 
Example 2
Source File: JsonConverter.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
public static List<KvEntry> parseValues(JsonObject valuesObject) {
  List<KvEntry> result = new ArrayList<>();
  for (Entry<String, JsonElement> valueEntry : valuesObject.entrySet()) {
    JsonElement element = valueEntry.getValue();
    if (element.isJsonPrimitive()) {
      JsonPrimitive value = element.getAsJsonPrimitive();
      if (value.isString()) {
        result.add(new StringDataEntry(valueEntry.getKey(), value.getAsString()));
      } else if (value.isBoolean()) {
        result.add(new BooleanDataEntry(valueEntry.getKey(), value.getAsBoolean()));
      } else if (value.isNumber()) {
        if (value.getAsString().contains(".")) {
          result.add(new DoubleDataEntry(valueEntry.getKey(), value.getAsDouble()));
        } else {
          result.add(new LongDataEntry(valueEntry.getKey(), value.getAsLong()));
        }
      } else {
        throw new JsonSyntaxException("Can't parse value: " + value);
      }
    } else {
      throw new JsonSyntaxException("Can't parse value: " + element);
    }
  }
  return result;
}
 
Example 3
Source File: Indexes.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Utility to list indexes of a given type.
 *
 * @param type      the type of index to list, null means all types
 * @param modelType the class to deserialize the index into
 * @param <T>       the type of the index
 * @return the list of indexes of the specified type
 */
private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {
    List<T> indexesOfType = new ArrayList<T>();
    Gson g = new Gson();
    for (JsonElement index : indexes) {
        if (index.isJsonObject()) {
            JsonObject indexDefinition = index.getAsJsonObject();
            JsonElement indexType = indexDefinition.get("type");
            if (indexType != null && indexType.isJsonPrimitive()) {
                JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();
                if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive
                        .getAsString().equals(type))) {
                    indexesOfType.add(g.fromJson(indexDefinition, modelType));
                }
            }
        }
    }
    return indexesOfType;
}
 
Example 4
Source File: MapTypeAdapterFactory.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
private String keyToString(JsonElement keyElement) {
  if (keyElement.isJsonPrimitive()) {
    JsonPrimitive primitive = keyElement.getAsJsonPrimitive();
    if (primitive.isNumber()) {
      return String.valueOf(primitive.getAsNumber());
    } else if (primitive.isBoolean()) {
      return Boolean.toString(primitive.getAsBoolean());
    } else if (primitive.isString()) {
      return primitive.getAsString();
    } else {
      throw new AssertionError();
    }
  } else if (keyElement.isJsonNull()) {
    return "null";
  } else {
    throw new AssertionError();
  }
}
 
Example 5
Source File: JsonUtil.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
private static int findPrimitive(JsonPrimitive element, JsonArray array) {
	Iterator<JsonElement> iterator = array.iterator();
	int index = 0;
	while (iterator.hasNext()) {
		JsonElement next = iterator.next();
		if (!next.isJsonPrimitive()) {
			index++;
			continue;
		}
		JsonPrimitive other = next.getAsJsonPrimitive();
		if (other.equals(element))
			return index;
		index++;
	}
	return -1;
}
 
Example 6
Source File: JsonUtils.java    From ProtocolSupport with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String toString(JsonElement jsonElement) {
	String abbreviateMiddle = String.valueOf(jsonElement);
	if (jsonElement == null) {
		return "null (missing)";
	}
	if (jsonElement.isJsonNull()) {
		return "null (json)";
	}
	if (jsonElement.isJsonArray()) {
		return "an array (" + abbreviateMiddle + ")";
	}
	if (jsonElement.isJsonObject()) {
		return "an object (" + abbreviateMiddle + ")";
	}
	if (jsonElement.isJsonPrimitive()) {
		JsonPrimitive asJsonPrimitive = jsonElement.getAsJsonPrimitive();
		if (asJsonPrimitive.isNumber()) {
			return "a number (" + abbreviateMiddle + ")";
		}
		if (asJsonPrimitive.isBoolean()) {
			return "a boolean (" + abbreviateMiddle + ")";
		}
	}
	return abbreviateMiddle;
}
 
Example 7
Source File: ConfigurationDeserializer.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private Configuration deserialize(JsonObject propertiesObject) {
    Configuration configuration = new Configuration();
    for (Entry<String, JsonElement> entry : propertiesObject.entrySet()) {
        JsonElement value = entry.getValue();
        String key = entry.getKey();
        if (value.isJsonPrimitive()) {
            JsonPrimitive primitive = value.getAsJsonPrimitive();
            configuration.put(key, deserialize(primitive));
        } else if (value.isJsonArray()) {
            JsonArray array = value.getAsJsonArray();
            configuration.put(key, deserialize(array));
        } else {
            throw new IllegalArgumentException(
                    "Configuration parameters must be primitives or arrays of primities only but was " + value);
        }
    }
    return configuration;
}
 
Example 8
Source File: QueryOptions.java    From yawp with MIT License 5 votes vote down vote up
private Object getJsonObjectValue(JsonElement jsonElement) {
    if (jsonElement.isJsonArray()) {
        return getJsonObjectValueForArrays(jsonElement);
    }
    if (jsonElement.isJsonNull()) {
        return null;
    }

    JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();

    if (jsonPrimitive.isNumber()) {
        if (jsonPrimitive.getAsString().indexOf(".") != -1) {
            return jsonPrimitive.getAsDouble();
        }
        return jsonPrimitive.getAsLong();
    }

    if (jsonPrimitive.isString()) {
        return jsonPrimitive.getAsString();
    }

    if (jsonPrimitive.isBoolean()) {
        return jsonPrimitive.getAsBoolean();
    }

    // TODO timestamp
    throw new RuntimeException("Invalid json value: " + jsonPrimitive.getAsString());
}
 
Example 9
Source File: IndexTests.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
private void assertUseIndexString(JsonElement useIndex) throws Exception {
    assertNotNull(useIndex, "The use_index property should not be null");
    assertTrue(useIndex.isJsonPrimitive(), "The use_index property should be a JsonPrimitive");
    JsonPrimitive useIndexPrimitive = useIndex.getAsJsonPrimitive();
    assertTrue(useIndexPrimitive.isString(), "The use_index property should be a string");
    String useIndexString = useIndexPrimitive.getAsString();
    assertEquals("Movie_year", useIndexString, "The use_index property should be Movie_year");
}
 
Example 10
Source File: MobileServiceTableBase.java    From azure-mobile-apps-android-client with Apache License 2.0 5 votes vote down vote up
/**
 * @return the numeric value represented by the object.
 *
 * @param o the object for which numberic value is to be extracted
 */
protected long getNumericValue(Object o) {
    long result;

    if (o instanceof Integer) {
        result = (Integer) o;
    } else if (o instanceof Long) {
        result = (Long) o;
    } else if (o instanceof JsonElement) {
        JsonElement json = (JsonElement) o;

        if (json.isJsonPrimitive()) {
            JsonPrimitive primitive = json.getAsJsonPrimitive();

            if (primitive.isNumber()) {
                result = primitive.getAsLong();
            } else {
                throw new IllegalArgumentException("Object does not represent a string value.");
            }
        } else {
            throw new IllegalArgumentException("Object does not represent a string value.");
        }
    } else {
        throw new IllegalArgumentException("Object does not represent a string value.");
    }

    return result;
}
 
Example 11
Source File: BackupManager.java    From revolution-irc with GNU General Public License v3.0 5 votes vote down vote up
@SuppressLint("ApplySharedPref")
private static void importPreferencesFromJson(Context context, Reader reader) {
    SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
    SettingsHelper.getInstance(context).clear();
    JsonObject obj = SettingsHelper.getGson().fromJson(reader, JsonObject.class);
    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
        JsonElement el = entry.getValue();
        if (el.isJsonArray()) {
            Set<String> items = new HashSet<>();
            for (JsonElement child : el.getAsJsonArray())
                items.add(child.getAsString());
            prefs.putStringSet(entry.getKey(), items);
        } else {
            JsonPrimitive primitive = el.getAsJsonPrimitive();
            if (primitive.isBoolean()) {
                prefs.putBoolean(entry.getKey(), primitive.getAsBoolean());
            } else if (primitive.isNumber()) {
                Number number = primitive.getAsNumber();
                if (number instanceof Float || number instanceof Double)
                    prefs.putFloat(entry.getKey(), number.floatValue());
                else if (number instanceof Long)
                    prefs.putLong(entry.getKey(), number.longValue());
                else
                    prefs.putInt(entry.getKey(), number.intValue());
            } else if (primitive.isString()) {
                prefs.putString(entry.getKey(), primitive.getAsString());
            }
        }
    }
    prefs.commit(); // This will be called asynchronously
}
 
Example 12
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public void write(JsonWriter out, JsonElement value) throws IOException {
    if (value == null || value.isJsonNull()) {
        out.nullValue();
    } else if (value.isJsonPrimitive()) {
        JsonPrimitive primitive = value.getAsJsonPrimitive();
        if (primitive.isNumber()) {
            out.value(primitive.getAsNumber());
        } else if (primitive.isBoolean()) {
            out.value(primitive.getAsBoolean());
        } else {
            out.value(primitive.getAsString());
        }
    } else if (value.isJsonArray()) {
        out.beginArray();
        i$ = value.getAsJsonArray().iterator();
        while (i$.hasNext()) {
            write(out, (JsonElement) i$.next());
        }
        out.endArray();
    } else if (value.isJsonObject()) {
        out.beginObject();
        for (Entry<String, JsonElement> e : value.getAsJsonObject().entrySet()) {
            out.name((String) e.getKey());
            write(out, (JsonElement) e.getValue());
        }
        out.endObject();
    } else {
        throw new IllegalArgumentException("Couldn't write " + value.getClass());
    }
}
 
Example 13
Source File: ConfigurationDeserializer.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private Object deserialize(JsonArray array) {
    List<Object> list = new LinkedList<>();
    for (JsonElement element : array) {
        if (element.isJsonPrimitive()) {
            JsonPrimitive primitive = element.getAsJsonPrimitive();
            list.add(deserialize(primitive));
        } else {
            throw new IllegalArgumentException("Multiples must only contain primitives but was " + element);
        }
    }
    return list;
}
 
Example 14
Source File: JsonValueExtractor.java    From json-logic-java with MIT License 5 votes vote down vote up
public static Object extract(JsonElement element) {
  if (element.isJsonObject()) {
    Map<String, Object> map = new HashMap<>();
    JsonObject object = element.getAsJsonObject();

    for (String key : object.keySet()) {
      map.put(key, extract(object.get(key)));
    }

    return map;
  }
  else if (element.isJsonArray()) {
    List<Object> values = new ArrayList<>();

    for (JsonElement item : element.getAsJsonArray()) {
      values.add(extract(item));
    }

    return values;
  }
  else if (element.isJsonNull()) {
    return null;
  }
  else if (element.isJsonPrimitive()) {
    JsonPrimitive primitive = element.getAsJsonPrimitive();

    if (primitive.isBoolean()) {
      return primitive.getAsBoolean();
    }
    else if (primitive.isNumber()) {
      return primitive.getAsNumber().doubleValue();
    }
    else {
      return primitive.getAsString();
    }
  }

  return element.toString();
}
 
Example 15
Source File: ConfigurationDeserializer.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private Object deserialize(JsonArray array) {
    List<Object> list = new LinkedList<>();
    for (JsonElement element : array) {
        if (element.isJsonPrimitive()) {
            JsonPrimitive primitive = element.getAsJsonPrimitive();
            list.add(deserialize(primitive));
        } else {
            throw new IllegalArgumentException("Multiples must only contain primitives but was " + element);
        }
    }
    return list;
}
 
Example 16
Source File: NaturalLanguageValueAdapter.java    From activitystreams with Apache License 2.0 5 votes vote down vote up
/**
 * Method deserialize.
 * @param element JsonElement
 * @param type1 Type
 * @param context JsonDeserializationContext



 * @return NLV * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */
public NLV deserialize(
  JsonElement element, 
  Type type1,
  JsonDeserializationContext context)
    throws JsonParseException {
  checkArgument(
    element.isJsonPrimitive() || 
    element.isJsonObject());
  if (element.isJsonPrimitive()) {
    JsonPrimitive prim = 
      element.getAsJsonPrimitive();
    checkArgument(prim.isString());
    return NLV.SimpleNLV.make(
      prim.getAsString());
  } else {
    try {
      JsonObject obj = 
        element.getAsJsonObject();
      NLV.MapNLV.Builder builder = 
        NLV.MapNLV.make();
      for (Entry<String,JsonElement> entry : obj.entrySet())
        builder.set(
          entry.getKey(), 
          entry.getValue().getAsString());  
      return builder.get();
    } catch (Throwable t) {
      throw new IllegalArgumentException();
    }
  }
}
 
Example 17
Source File: TypeValueAdapter.java    From activitystreams with Apache License 2.0 5 votes vote down vote up
/**
 * Method deserialize.
 * @param el JsonElement
 * @param type Type
 * @param context JsonDeserializationContext



 * @return TypeValue * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */
public TypeValue deserialize(
  JsonElement el, 
  Type type,
  JsonDeserializationContext context) 
    throws JsonParseException {
  checkArgument(
    el.isJsonPrimitive() || 
    el.isJsonObject());
  if (el.isJsonPrimitive()) {
    JsonPrimitive prim = 
      el.getAsJsonPrimitive();
    checkArgument(prim.isString());
    return type(prim.getAsString());
  } else {
    JsonObject obj = el.getAsJsonObject();
    if (obj.has("objectType")) {
      TypeValue tv = 
        context.deserialize(
          obj.get("objectType"), 
          TypeValue.class);
      Model pMap = 
        schema.forObjectType(tv.id());
      return 
        context.<ASObject>deserialize(
          el, 
          pMap.type() != null ? 
            pMap.type() : 
            ASObject.class);
    } else {
      return 
        context.<ASObject>deserialize(
          el, 
          ASObject.class);
    }
  }
}
 
Example 18
Source File: GsonDeserializerObjectWrapper.java    From qaf with MIT License 4 votes vote down vote up
private Object read(JsonElement in, Type typeOfT) {
	
	if (in.isJsonArray()) {
		JsonArray arr = in.getAsJsonArray();

		boolean isArray = isArray(typeOfT);
		Collection<Object> list = isArray ? new ArrayList<Object>()
				: context.deserialize(new JsonArray(0), typeOfT);
		for (JsonElement anArr : arr) {
			((Collection<Object>) list).add(read(anArr, getTypeArguments(typeOfT, 0)));
		}
		if (isArray) {
			return toArray((List<Object>) list);
		}
		try {
			return ClassUtil.getClass(typeOfT).cast(list);
		} catch (Exception e) {
			return context.deserialize(in, typeOfT);
		}
	} else if (in.isJsonObject()
			&& (isAssignableFrom(typeOfT, Map.class) || ClassUtil.getClass(typeOfT).equals(Object.class))) {
		Map<Object, Object> map = context.deserialize(new JsonObject(), typeOfT);//new LinkedTreeMap<Object, Object>();
		JsonObject obj = in.getAsJsonObject();
		Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
		for (Map.Entry<String, JsonElement> entry : entitySet) {
			map.put(entry.getKey(), read(entry.getValue(), getTypeArguments(typeOfT, 1)));
		}
		return map;
	} else if (in.isJsonPrimitive() && ClassUtil.getClass(typeOfT).equals(Object.class)) {
		JsonPrimitive prim = in.getAsJsonPrimitive();
		if (prim.isBoolean()) {
			return prim.getAsBoolean();
		} else if (prim.isString()) {
			return prim.getAsString();
		} else if (prim.isNumber()) {
			if (prim.getAsString().contains("."))
				return prim.getAsDouble();
			else {
				return prim.getAsLong();
			}
		}
	}
	return context.deserialize(in, typeOfT);
}
 
Example 19
Source File: DataUtil.java    From Prism with MIT License 4 votes vote down vote up
/**
 * Attempts to convert a JsonElement to an a known type.
 *
 * @param element JsonElement
 * @return Optional<Object>
 */
private static Optional<Object> jsonElementToObject(JsonElement element) {
    if (element.isJsonArray()) {
        List<Object> list = Lists.newArrayList();
        JsonArray jsonArray = element.getAsJsonArray();
        jsonArray.forEach(entry -> jsonElementToObject(entry).ifPresent(list::add));
        return Optional.of(list);
    } else if (element.isJsonObject()) {
        JsonObject jsonObject = element.getAsJsonObject();
        PrimitiveArray primitiveArray = PrimitiveArray.of(jsonObject);
        if (primitiveArray != null) {
            return Optional.of(primitiveArray.getArray());
        }

        return Optional.of(dataViewFromJson(jsonObject));
    } else if (element.isJsonPrimitive()) {
        JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive();
        if (jsonPrimitive.isBoolean()) {
            return Optional.of(jsonPrimitive.getAsBoolean());
        } else if (jsonPrimitive.isNumber()) {
            Number number = NumberUtils.createNumber(jsonPrimitive.getAsString());
            if (number instanceof Byte) {
                return Optional.of(number.byteValue());
            } else if (number instanceof Double) {
                return Optional.of(number.doubleValue());
            } else if (number instanceof Float) {
                return Optional.of(number.floatValue());
            } else if (number instanceof Integer) {
                return Optional.of(number.intValue());
            } else if (number instanceof Long) {
                return Optional.of(number.longValue());
            } else if (number instanceof Short) {
                return Optional.of(number.shortValue());
            }
        } else if (jsonPrimitive.isString()) {
            return Optional.of(jsonPrimitive.getAsString());
        }
    }

    return Optional.empty();
}
 
Example 20
Source File: ParameterAdapter.java    From activitystreams with Apache License 2.0 4 votes vote down vote up
@Override
public ParameterValue deserialize(
  JsonElement json, 
  Type typeOfT,
  JsonDeserializationContext context) 
    throws JsonParseException {

  checkArgument(json.isJsonPrimitive() || json.isJsonObject());
  
  if (json.isJsonPrimitive()) {
    JsonPrimitive jp = json.getAsJsonPrimitive();
    checkArgument(jp.isString());
    return ActionMakers.parameter(jp.getAsString());
  } else {
    JsonObject obj = json.getAsJsonObject();
    if (obj.has("objectType")) {
      ASObject as = context.deserialize(obj, ASObject.class);
      checkArgument(as instanceof ParameterValue);
      return (ParameterValue) as;
    } else {
      Parameter.Builder builder =
        ActionMakers.parameter();
      if (obj.has("default"))
        builder.defaultValue(
          deserialize(context, obj.get("default")));
      if (obj.has("displayName"))
        builder.displayName(
          context.<NLV>deserialize(
            obj.get("displayName"), 
            NLV.class));
      if (obj.has("enumeration"))
        builder.enumeration(
          context.<Iterable<?>>deserialize(
            obj.get("enumeration"), 
            Iterable.class));
      if (obj.has("fractionDigits"))
        builder.fractionDigits(
          obj.get("fractionDigits").getAsInt());
      if (obj.has("language"))
        builder.language(
          obj.get("language").getAsString());
      if (obj.has("maxExclusive"))
        builder.maxExclusive(
          deserialize(context, obj.get("maxExclusive")));
      if (obj.has("maxInclusive"))
        builder.maxInclusive(
            deserialize(context, obj.get("maxInclusive")));
      if (obj.has("minExclusive"))
        builder.minExclusive(
            deserialize(context, obj.get("minExclusive")));
      if (obj.has("minInclusive"))
        builder.minInclusive(
          deserialize(context, obj.get("minInclusive")));
      if (obj.has("maxLength"))
        builder.maxLength(
          obj.get("maxLength").getAsInt());
      if (obj.has("minLength"))
        builder.minLength(
          obj.get("minLength").getAsInt());
      if (obj.has("pattern"))
        builder.pattern(
          context.<Iterable<String>>deserialize(
            obj.get("pattern"), Iterable.class));
      if (obj.has("placeholder"))
        builder.placeholder(
          context.<NLV>deserialize(
            obj.get("placeholder"), NLV.class));
      if (obj.has("repeated") && obj.get("repeated").getAsBoolean())
          builder.repeated();
      if (obj.has("required") && !obj.get("required").getAsBoolean())
          builder.optional();
      if (obj.has("step")) 
        builder.step(
          obj.get("step").getAsNumber());
      if (obj.has("totalDigits")) 
        builder.totalDigits(
          obj.get("totalDigits").getAsInt());
      if (obj.has("type"))
        builder.type(
          obj.get("type").getAsString());
      if (obj.has("value"))
        builder.value(
            deserialize(context, obj.get("value")));
      return builder.get();
    }
  }
}