Java 类com.google.gson.JsonPrimitive 实例源码
项目:gremzeppelin
文件:GremlinInterpreter.java
@Override
public InterpreterResult interpret(String gremlin, InterpreterContext interpreterContext) {
logger.info("execute gremlin traversal {}", gremlin);
try {
ResultSet results = client.submit(gremlin);
JsonArray array = results.stream()
.map(result -> new JsonPrimitive(results.toString()))
.collect(JsonArray::new, JsonArray::add, JsonArray::addAll);
//TODO extract ResultSet
//Case MessageSerializer
return new InterpreterResult(InterpreterResult.Code.SUCCESS, array.toString());
} catch (RuntimeException e) {
return new InterpreterResult(InterpreterResult.Code.ERROR, e.getMessage());
}
}
项目:seldon-core
文件:JsonFormat.java
private void mergeMapField(FieldDescriptor field, JsonElement json, Message.Builder builder)
throws InvalidProtocolBufferException {
if (!(json instanceof JsonObject)) {
throw new InvalidProtocolBufferException("Expect a map object but found: " + json);
}
Descriptor type = field.getMessageType();
FieldDescriptor keyField = type.findFieldByName("key");
FieldDescriptor valueField = type.findFieldByName("value");
if (keyField == null || valueField == null) {
throw new InvalidProtocolBufferException("Invalid map field: " + field.getFullName());
}
JsonObject object = (JsonObject) json;
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
Message.Builder entryBuilder = builder.newBuilderForField(field);
Object key = parseFieldValue(keyField, new JsonPrimitive(entry.getKey()), entryBuilder);
Object value = parseFieldValue(valueField, entry.getValue(), entryBuilder);
if (value == null) {
throw new InvalidProtocolBufferException("Map value cannot be null.");
}
entryBuilder.setField(keyField, key);
entryBuilder.setField(valueField, value);
builder.addRepeatedField(field, entryBuilder.build());
}
}
项目:ctsms
文件:IndexResource.java
private static JsonElement createVOInputTypeNode(Class inputType, Type genericType) throws Exception {
// no input maps:
if (isTerminalType(inputType)) {
return new JsonPrimitive(ClassUtils.getSimpleName(inputType));
} else {
boolean isCollection = Collection.class.isAssignableFrom(inputType);
if (isCollection) {
try {
inputType = (Class) ((ParameterizedType) genericType).getActualTypeArguments()[0];
} catch (Exception e) {
inputType = Object.class;
}
}
Collection<Method> fields = AssociationPath.listMethods(inputType, VO_METHOD_TRANSFILTER);
if (isTerminalType(inputType) || fields.size() == 0) {
return markMapCollection(new JsonPrimitive(ClassUtils.getSimpleName(inputType)), null, false, isCollection);
} else {
return markMapCollection(createVONode(fields, true), null, false, isCollection);
}
}
}
项目:HuskyUI-Plugin
文件:Metrics.java
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JsonArray categoryValues = new JsonArray();
categoryValues.add(new JsonPrimitive(entry.getValue()));
values.add(entry.getKey(), categoryValues);
}
data.add("values", values);
return data;
}
项目:unitimes
文件:EventsExportEventsToJSON.java
@Override
protected void print(ExportHelper helper, EventLookupRpcRequest request, List<EventInterface> events, int eventCookieFlags, EventMeetingSortBy sort, boolean asc) throws IOException {
helper.setup("application/json", reference(), false);
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
}
})
.setFieldNamingStrategy(new FieldNamingStrategy() {
Pattern iPattern = Pattern.compile("i([A-Z])(.*)");
@Override
public String translateName(Field f) {
Matcher matcher = iPattern.matcher(f.getName());
if (matcher.matches())
return matcher.group(1).toLowerCase() + matcher.group(2);
else
return f.getName();
}
})
.setPrettyPrinting().create();
helper.getWriter().write(gson.toJson(events));
}
项目:iotplatform
文件:JsonConverter.java
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;
}
项目:SurvivalAPI
文件:SurvivalPlugin.java
/**
* Called on when plugin enables
*/
@Override
public void onEnable()
{
this.worldLoader = new WorldLoader(this, SamaGamesAPI.get().getGameManager().getGameProperties().getGameOption("size", new JsonPrimitive(1000)).getAsInt());
this.api = new SurvivalAPI(this);
try
{
NMSPatcher nmsPatcher = new NMSPatcher(this);
nmsPatcher.patchBiomes();
nmsPatcher.patchPotions();
if (SamaGamesAPI.get().getGameManager().getGameProperties().getGameOption("patch-stackable", new JsonPrimitive(false)).getAsBoolean())
nmsPatcher.patchStackable();
}
catch (Exception e)
{
this.getLogger().log(Level.SEVERE, "Error while patching NMS" , e);
}
this.getCommand("uhc").setExecutor(new CommandUHC());
this.getCommand("nextevent").setExecutor(new CommandNextEvent());
this.startTimer = this.getServer().getScheduler().runTaskTimer(this, this::postInit, 20L, 20L);
}
项目:seldon-core
文件:JsonFormat.java
private void mergeMapField(FieldDescriptor field, JsonElement json, Message.Builder builder)
throws InvalidProtocolBufferException {
if (!(json instanceof JsonObject)) {
throw new InvalidProtocolBufferException("Expect a map object but found: " + json);
}
Descriptor type = field.getMessageType();
FieldDescriptor keyField = type.findFieldByName("key");
FieldDescriptor valueField = type.findFieldByName("value");
if (keyField == null || valueField == null) {
throw new InvalidProtocolBufferException("Invalid map field: " + field.getFullName());
}
JsonObject object = (JsonObject) json;
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
Message.Builder entryBuilder = builder.newBuilderForField(field);
Object key = parseFieldValue(keyField, new JsonPrimitive(entry.getKey()), entryBuilder);
Object value = parseFieldValue(valueField, entry.getValue(), entryBuilder);
if (value == null) {
throw new InvalidProtocolBufferException("Map value cannot be null.");
}
entryBuilder.setField(keyField, key);
entryBuilder.setField(valueField, value);
builder.addRepeatedField(field, entryBuilder.build());
}
}
项目:odoo-work
文件:MapTypeAdapterFactory.java
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();
}
}
项目:iosched-reader
文件:IntegerToStringConverter.java
@Override
public JsonPrimitive convert(JsonPrimitive value) {
if (value == null) {
return null;
}
if (value.isNumber()) {
return new JsonPrimitive(String.valueOf(value.getAsInt()));
}
try {
Integer.parseInt(value.getAsString());
// if it parses correctly, it is validated:
return value;
} catch (NumberFormatException ex) {
throw new ConverterException(value, this);
}
}
项目:Kineticraft
文件:JsonSerializer.java
/**
* Save a java object as serialized json.
* @param obj - The object to convert to json.
* @param forceJson - Force this object to be handled as if it was Jsonable.
* @return saved - The saved json.
*/
@SuppressWarnings("unchecked")
public static JsonElement save(Object obj, boolean forceJson) {
JsonData data = new JsonData();
if (obj instanceof Jsonable || forceJson) {
getFields(obj).forEach(f -> {
try {
getHandler(f).saveField(data, f.get(obj), f.getName());
} catch (Exception e) {
e.printStackTrace();
}
});
return data.getJsonObject();
}
Object result = getHandler(obj.getClass()).serialize(obj);
if (result instanceof JsonData)
return ((JsonData) result).getJsonObject();
return result instanceof JsonElement ? (JsonElement) result : ReflectionUtil.construct(JsonPrimitive.class, result);
}
项目:ProjectAres
文件:ConfigUtils.java
private static JsonElement toJson(Object value) {
if(value instanceof ConfigurationSection) {
return toJson((ConfigurationSection) value);
} else if(value instanceof Map) {
return toJson((Map) value);
} else if(value instanceof List) {
return toJson((List) value);
} else if(value instanceof String) {
return new JsonPrimitive((String) value);
} else if(value instanceof Character) {
return new JsonPrimitive((Character) value);
} else if(value instanceof Number) {
return new JsonPrimitive((Number) value);
} else if(value instanceof Boolean) {
return new JsonPrimitive((Boolean) value);
} else if(value == null) {
return JsonNull.INSTANCE;
} else {
throw new IllegalArgumentException("Cannot coerce " + value.getClass().getSimpleName() + " to JSON");
}
}
项目:ja-micro
文件:RegistrationManager.java
private JsonArray getRegistrationTags() throws IOException {
JsonArray retval = new JsonArray();
String tag = "{\"type\":\"" + getShortServiceName() + "\"}";
retval.add(new JsonPrimitive("t-" + binaryEncode(tag)));
tag = "{\"transport\":\"http\"}";
retval.add(new JsonPrimitive("t-" + binaryEncode(tag)));
tag = "{\"broker\":\"http\"}";
retval.add(new JsonPrimitive("t-" + binaryEncode(tag)));
tag = "{\"server\":\"rpc\"}";
retval.add(new JsonPrimitive("t-" + binaryEncode(tag)));
tag = "{\"registry\":\"consul\"}";
retval.add(new JsonPrimitive("t-" + binaryEncode(tag)));
addEndpointsTags(retval);
tag = getServiceVersion();
retval.add(new JsonPrimitive("v-" + binaryEncode(tag)));
return retval;
}
项目:RainServer
文件:CommandPrice.java
private void update() {
try {
URLConnection conn = new URL(url).openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
String json = "";
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
json = reader.lines().collect(Collectors.joining("\n"));
}
json = json.trim().replaceAll("\\[", "").replaceAll("\\]", ""); //quick and dirty fix
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
JsonPrimitive priceDollars = jsonObject.getAsJsonPrimitive("price_usd");
price = priceDollars.getAsString();
int maxIndex = price.indexOf(".") + 3;
if (price.length() >= maxIndex)
price = price.substring(0, maxIndex);
} catch (Exception e) {
e.printStackTrace();
price = "0.00";
}
price = "{\"price\":\"" + price + "\"}";
}
项目:iosched-reader
文件:DataExtractor.java
private void setVideoPropertiesInSession(JsonObject origin, JsonObject dest) {
boolean isLivestream = isLivestreamed(origin);
set(new JsonPrimitive(isLivestream), dest, OutputJsonKeys.Sessions.isLivestream);
JsonPrimitive vid = null;
if (isLivestream) {
vid = getVideoFromTopicInfo(origin, InputJsonKeys.VendorAPISource.Topics.INFO_STREAM_VIDEO_ID,
Config.VIDEO_LIVESTREAMURL_FOR_EMPTY);
} else {
vid = getMapValue(
get(origin, InputJsonKeys.VendorAPISource.Topics.info), InputJsonKeys.VendorAPISource.Topics.INFO_VIDEO_URL,
Converters.YOUTUBE_URL, null);
}
if (vid != null && !vid.getAsString().isEmpty()) {
set(vid, dest, OutputJsonKeys.Sessions.youtubeUrl);
}
}
项目:Phoenix-for-VK
文件:DboWrapperAdapter.java
@Override
public JsonElement serialize(EntityWrapper wrapper, Type type, JsonSerializationContext context) {
if (wrapper == null) {
return JsonNull.INSTANCE;
}
JsonObject root = new JsonObject();
Entity entity = wrapper.get();
root.add(KEY_IS_NULL, new JsonPrimitive(entity == null));
if (entity != null) {
root.add(KEY_TYPE, new JsonPrimitive(AttachmentsTypes.typeForInstance(entity)));
root.add(KEY_ENTITY, context.serialize(entity));
}
return root;
}
项目:bStats-Metrics
文件:Metrics.java
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JsonArray categoryValues = new JsonArray();
categoryValues.add(new JsonPrimitive(entry.getValue()));
values.add(entry.getKey(), categoryValues);
}
data.add("values", values);
return data;
}
项目:IPE-LWM2M
文件:LwM2mNodeDeserializer.java
private Object deserializeValue(JsonPrimitive val, org.eclipse.leshan.core.model.ResourceModel.Type expectedType) {
switch (expectedType) {
case BOOLEAN:
return val.getAsBoolean();
case STRING:
return val.getAsString();
case INTEGER:
return val.getAsLong();
case FLOAT:
return val.getAsDouble();
case TIME:
case OPAQUE:
default:
// TODO we need to better handle this.
return val.getAsString();
}
}
项目:SOS-The-Healthcare-Companion
文件:DeleteQuery.java
public Call<DeleteResult<R>, DBException> build() {
/* Create the query object */
JsonObject query = new JsonObject();
if (this.whereExp != null)
query.add("where", this.whereExp);
if (this.retSet.size() != 0) {
JsonArray retArr = new JsonArray();
for (String retCol : this.retSet)
retArr.add(new JsonPrimitive(retCol));
query.add("returning", retArr);
}
String opUrl = "/table/" + table.getTableName() + "/delete";
Converter<DeleteResult<R>, DBException> converter
= new DBResponseConverter<>(table.getDelResType());
return db.mkCall(opUrl, db.gson.toJson(query), converter);
}
项目:neoscada
文件:VariantJsonDeserializer.java
private Variant decodeFromPrimitive ( final JsonElement json )
{
final JsonPrimitive jsonPrim = (JsonPrimitive)json;
if ( jsonPrim.isBoolean () )
{
return Variant.valueOf ( jsonPrim.getAsBoolean () );
}
else if ( jsonPrim.isNumber () )
{
return Variant.valueOf ( jsonPrim.getAsNumber () );
}
else
{
return VariantEditor.toVariant ( jsonPrim.getAsString () );
}
}
项目:SOS-The-Healthcare-Companion
文件:UpdateQuery.java
public Call<UpdateResult<R>, DBException> build() {
/* Create the query object */
JsonObject query = new JsonObject();
query.add("$set", this.setObj);
if (this.whereExp != null)
query.add("where", this.whereExp);
if (this.retSet.size() != 0) {
JsonArray retArr = new JsonArray();
for (String retCol : this.retSet)
retArr.add(new JsonPrimitive(retCol));
query.add("returning", retArr);
}
String opUrl = "/table/" + table.getTableName() + "/update";
Converter<UpdateResult<R>, DBException> converter
= new DBResponseConverter<>(table.getUpdResType());
return db.mkCall(opUrl, db.gson.toJson(query), converter);
}
项目:iosched-reader
文件:TagNameConverter.java
@Override
public JsonPrimitive convert(JsonPrimitive value) {
if (value == null) {
return null;
}
return new JsonPrimitive(value.getAsString().toUpperCase().replace('/', '_').replaceAll("[ ']",""));
}
项目:iosched-reader
文件:DataExtractor.java
private JsonPrimitive getVideoFromTopicInfo(JsonObject origin, String sourceInfoKey, String defaultVideoUrl) {
JsonPrimitive result = null;
if (!obfuscate) {
JsonPrimitive vid = getMapValue(
get(origin, InputJsonKeys.VendorAPISource.Topics.info), sourceInfoKey, null, defaultVideoUrl);
if (vid != null && !vid.getAsString().isEmpty()) {
result = vid;
}
}
return (result == null && defaultVideoUrl != null) ? new JsonPrimitive(defaultVideoUrl) : result;
}
项目:DecompiledMinecraft
文件:JsonSerializableSet.java
/**
* Gets the JsonElement that can be serialized.
*/
public JsonElement getSerializableElement()
{
JsonArray jsonarray = new JsonArray();
for (String s : this)
{
jsonarray.add(new JsonPrimitive(s));
}
return jsonarray;
}
项目:bStats-Metrics
文件:Metrics.java
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JsonArray categoryValues = new JsonArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(new JsonPrimitive(categoryValue));
}
values.add(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
项目:graphouse
文件:MetricDataRowCallbackHandlerTest.java
private JsonArray createPoints(double... values) {
JsonArray points = new JsonArray();
for (double value : values) {
if (Double.isFinite(value)) {
points.add(new JsonPrimitive(value));
} else {
points.add(JsonNull.INSTANCE);
}
}
return points;
}
项目:iosched-reader
文件:DataExtractor.java
private boolean isHiddenSession(JsonObject sessionObj) {
JsonPrimitive hide = getMapValue(
get(sessionObj, InputJsonKeys.VendorAPISource.Topics.info),
InputJsonKeys.VendorAPISource.Topics.INFO_HIDDEN_SESSION,
Converters.BOOLEAN, null);
if (hide != null && hide.isBoolean() && hide.getAsBoolean()) {
return true;
}
return false;
}
项目:MyRepository
文件:StringConverter.java
public JsonElement serialize(String src, Type typeOfSrc, JsonSerializationContext context) {
if (src == null) {
return new JsonPrimitive("");
} else {
return new JsonPrimitive(src.toString());
}
}
项目:seldon-core
文件:QuantityUtils.java
@Override
public void merge(JsonElement json, Builder builder) throws InvalidProtocolBufferException {
if (json instanceof JsonPrimitive) {
JsonPrimitive primitive = (JsonPrimitive) json;
if (primitive.isString())
{
Quantity.Builder b = Quantity.newBuilder().setString(primitive.getAsString());
builder.mergeFrom(b.build().toByteArray());
}
else throw new InvalidProtocolBufferException("Can't decode io.kubernetes.client.proto.resource.Quantity from "+json.toString());
}
}
项目:n5
文件:GsonAttributesParser.java
/**
* Best effort implementation of {@link N5Reader#listAttributes(String)}
* with limited type resolution. Possible return types are
* <ul>
* <li>null</li>
* <li>boolean</li>
* <li>double</li>
* <li>String</li>
* <li>Object</li>
* <li>boolean[]</li>
* <li>double[]</li>
* <li>String[]</li>
* <li>Object[]</li>
* </ul>
*/
@Override
public default Map<String, Class<?>> listAttributes(String pathName) throws IOException {
HashMap<String, JsonElement> jsonElementMap = getAttributes(pathName);
final HashMap<String, Class<?>> attributes = new HashMap<>();
jsonElementMap.forEach(
(key, jsonElement) -> {
final Class<?> clazz;
if (jsonElement.isJsonNull())
clazz = null;
else if (jsonElement.isJsonPrimitive())
clazz = classForJsonPrimitive((JsonPrimitive)jsonElement);
else if (jsonElement.isJsonArray()) {
final JsonArray jsonArray = (JsonArray)jsonElement;
if (jsonArray.size() > 0) {
final JsonElement firstElement = jsonArray.get(0);
if (firstElement.isJsonPrimitive())
clazz = Array.newInstance(classForJsonPrimitive((JsonPrimitive)firstElement), 0).getClass();
else
clazz = Object[].class;
}
else
clazz = Object[].class;
}
else
clazz = Object.class;
attributes.put(key, clazz);
});
return attributes;
}
项目:revolution-irc
文件:BackupManager.java
@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
}
项目:SayNoToMcLeaks
文件:Metrics.java
@Override
protected JsonObject getChartData() {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
HashMap<String, int[]> map = getValues(new HashMap<String, int[]>());
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JsonArray categoryValues = new JsonArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(new JsonPrimitive(categoryValue));
}
values.add(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
项目:iosched-reader
文件:DataModelHelperTest.java
/**
* Test method for {@link com.google.iosched.model.DataModelHelper#set(com.google.gson.JsonObject, java.lang.Enum, com.google.gson.JsonObject, java.lang.Enum, com.google.iosched.model.validator.Converter)}.
* @throws IOException
*/
@Test
public void testSetInComplexObject() throws IOException {
JsonObject dest = (JsonObject) TestHelper.readJsonTestDataFile("sample_topic.json");
String originalValue = "testvalue";
Enum<?> destKey = InputJsonKeys.VendorAPISource.Rooms.name;
JsonPrimitive value = new JsonPrimitive(originalValue);
DataModelHelper.set(value, dest, destKey);
assertEquals(originalValue, dest.get(destKey.name()).getAsString());
}
项目:gradle-auto-version
文件:VersionDeserializerTest.java
@Test
public void shouldDeserializeincompleteJson() throws Exception {
JsonObject given = new JsonObject();
given.add("major", new JsonPrimitive(2));
given.add("patch", new JsonPrimitive(1));
Version version = testee.deserialize(given, null, null);
assertThat(version.getMajor(), is(2L));
assertThat(version.getMinor(), is(0L));
assertThat(version.getPatch(), is(1L));
assertThat(version.getLabel(), is(nullValue()));
}
项目:lams
文件:TypeAdapters.java
@Override public JsonElement read(JsonReader in) throws IOException {
switch (in.peek()) {
case STRING:
return new JsonPrimitive(in.nextString());
case NUMBER:
String number = in.nextString();
return new JsonPrimitive(new LazilyParsedNumber(number));
case BOOLEAN:
return new JsonPrimitive(in.nextBoolean());
case NULL:
in.nextNull();
return JsonNull.INSTANCE;
case BEGIN_ARRAY:
JsonArray array = new JsonArray();
in.beginArray();
while (in.hasNext()) {
array.add(read(in));
}
in.endArray();
return array;
case BEGIN_OBJECT:
JsonObject object = new JsonObject();
in.beginObject();
while (in.hasNext()) {
object.add(in.nextName(), read(in));
}
in.endObject();
return object;
case END_DOCUMENT:
case NAME:
case END_OBJECT:
case END_ARRAY:
default:
throw new IllegalArgumentException();
}
}
项目:EMC
文件:Settings.java
public synchronized void addNode(String node, String value) {
try {
JsonObject jsonObject = new Gson().fromJson(getConfigFileContents(), JsonObject.class);
if (jsonObject.has(node)) {
jsonObject.remove(node);
}
jsonObject.add(node, new JsonPrimitive(value));
flushConfig(jsonObject.toString());
} catch (Exception ex) {
;
}
}
项目:sepatools
文件:SPARQL11SEProperties.java
@Override
protected void defaults() {
super.defaults();
JsonObject subscribe = new JsonObject();
subscribe.add("port", new JsonPrimitive(9000));
subscribe.add("scheme", new JsonPrimitive("ws"));
subscribe.add("path", new JsonPrimitive("/sparql"));
parameters.add("subscribe", subscribe);
JsonObject securesubscribe = new JsonObject();
securesubscribe.add("port", new JsonPrimitive(9443));
securesubscribe.add("scheme", new JsonPrimitive("wss"));
securesubscribe.add("path", new JsonPrimitive("/secure/sparql"));
parameters.add("securesubscribe", securesubscribe);
JsonObject secureUpdate = new JsonObject();
secureUpdate.add("port", new JsonPrimitive(8443));
secureUpdate.add("scheme", new JsonPrimitive("https"));
parameters.add("secureupdate", secureUpdate);
JsonObject secureQuery = new JsonObject();
secureQuery.add("port", new JsonPrimitive(8443));
secureQuery.add("scheme", new JsonPrimitive("https"));
parameters.add("securequery", secureQuery);
JsonObject register = new JsonObject();
register.add("register", new JsonPrimitive("/oauth/register"));
register.add("requesttoken", new JsonPrimitive("/oauth/token"));
register.add("port", new JsonPrimitive(8443));
register.add("scheme", new JsonPrimitive("https"));
parameters.add("authorizationserver", register);
}
项目:sepatools
文件:SPARQL11SEProperties.java
/**
* Sets the credentials.
*
* @param id the username
* @param secret the password
* @throws IOException
*/
public void setCredentials(String id,String secret) throws IOException {
logger.debug("Set credentials Id: "+id+" Secret:"+secret);
this.id = id;
this.secret = secret;
try {
authorization = new BASE64Encoder().encode((id + ":" + secret).getBytes("UTF-8"));
//TODO need a "\n", why?
authorization = authorization.replace("\n", "");
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage());
}
//Save on file the encrypted version
if (parameters.get("security")==null) {
JsonObject credentials = new JsonObject();
credentials.add("client_id",new JsonPrimitive(SEPAEncryption.encrypt(id)));
credentials.add("client_secret",new JsonPrimitive(SEPAEncryption.encrypt(secret)));
parameters.add("security",credentials);
}
else {
parameters.get("security").getAsJsonObject().add("client_id",new JsonPrimitive(SEPAEncryption.encrypt(id)));
parameters.get("security").getAsJsonObject().add("client_secret",new JsonPrimitive(SEPAEncryption.encrypt(secret)));
}
storeProperties(propertiesFile);
}
项目:iosched-reader
文件:DataExtractor.java
/** Check whether a session is featured or not.
*
* @param sessionObj Session to check
* @return True if featured, false otherwise.
*/
private boolean isFeatured(JsonObject sessionObj) {
// Extract "Featured Session" flag from EventPoint "info" block.
JsonPrimitive featured = getMapValue(
get(sessionObj, InputJsonKeys.VendorAPISource.Topics.info),
InputJsonKeys.VendorAPISource.Topics.INFO_FEATURED_SESSION,
Converters.BOOLEAN, null);
if (featured != null && featured.isBoolean() && featured.getAsBoolean()) {
return true;
}
return false;
}
项目:odoo-work
文件:JsonTreeReader.java
@Override public long nextLong() throws IOException {
JsonToken token = peek();
if (token != JsonToken.NUMBER && token != JsonToken.STRING) {
throw new IllegalStateException("Expected " + JsonToken.NUMBER + " but was " + token);
}
long result = ((JsonPrimitive) peekStack()).getAsLong();
popStack();
return result;
}