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

The following examples show how to use com.google.gson.JsonElement#isJsonNull() . 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
private Set<ConstraintViolation<?>> validate(final String typeName, final String propertyName, final JsonElement propertyElement) {
    Assert.requireNonNull(propertyElement, "propertyElement");
    if (!propertyElement.isJsonPrimitive() && !propertyElement.isJsonNull()) {
        throw new IllegalArgumentException("Only primitive or null properties supported. Wrong type for " + typeName + "." + propertyName);
    }
    if (propertyElement.isJsonNull()) {
        return remoteValidator.validateValue(typeName, propertyName, null);
    }
    final JsonPrimitive primitiveValue = propertyElement.getAsJsonPrimitive();
    if (primitiveValue.isBoolean()) {
        return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsBoolean());
    } else if (primitiveValue.isNumber()) {
        return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsNumber());
    } else if (primitiveValue.isString()) {
        return remoteValidator.validateValue(typeName, propertyName, primitiveValue.getAsString());
    }
    throw new IllegalArgumentException("Not supported type for " + typeName + "." + propertyName);
}
 
Example 2
@Override
public void onUpdate(JsonElement data) {
    if (active && !(data.isJsonNull())) {
        state = new TradfriSensorData(data);
        updateStatus(state.getReachabilityStatus() ? ThingStatus.ONLINE : ThingStatus.OFFLINE);

        DecimalType batteryLevel = state.getBatteryLevel();
        if (batteryLevel != null) {
            updateState(CHANNEL_BATTERY_LEVEL, batteryLevel);
        }

        OnOffType batteryLow = state.getBatteryLow();
        if (batteryLow != null) {
            updateState(CHANNEL_BATTERY_LOW, batteryLow);
        }

        updateDeviceProperties(state);

        logger.debug(
                "Updating thing for sensorId {} to state {batteryLevel: {}, batteryLow: {}, firmwareVersion: {}, modelId: {}, vendor: {}}",
                state.getDeviceId(), batteryLevel, batteryLow, state.getFirmwareVersion(), state.getModelId(),
                state.getVendor());
    }
}
 
Example 3
public void refresh(){
    try {
        url = new URL("https://api.twitch.tv/kraken/streams/" + channel);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));

        // while((s = reader.readLine()) != null) {
        //   Log.info(s);
        JsonElement json = new JsonParser().parse(reader);
        JsonObject obj = json.getAsJsonObject();
        //   String title = obj.get("status").getAsString();
        JsonElement streaming = obj.get("stream");
        online = !streaming.isJsonNull();
        /* JsonArray array = json.getAsJsonArray();
         for(int i = 0; i < array.size(); i++) {
             Log.info(array.get(i).getAsString());
         }*/
        // Log.info(json.toString());
        // }

    } catch(Throwable e) {
        // e.printStackTrace();
    }
}
 
Example 4
Source Project: twill   File: TwillSpecificationCodec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public TwillSpecification deserialize(JsonElement json, Type typeOfT,
                                      JsonDeserializationContext context) throws JsonParseException {
  JsonObject jsonObj = json.getAsJsonObject();

  String name = jsonObj.get("name").getAsString();
  Map<String, RuntimeSpecification> runnables = context.deserialize(
    jsonObj.get("runnables"), new TypeToken<Map<String, RuntimeSpecification>>() { }.getType());
  List<TwillSpecification.Order> orders = context.deserialize(
    jsonObj.get("orders"), new TypeToken<List<TwillSpecification.Order>>() { }.getType());
  List<TwillSpecification.PlacementPolicy> placementPolicies = context.deserialize(
    jsonObj.get("placementPolicies"), new TypeToken<List<TwillSpecification.PlacementPolicy>>() { }.getType());

  JsonElement handler = jsonObj.get("handler");
  EventHandlerSpecification eventHandler = null;
  if (handler != null && !handler.isJsonNull()) {
    eventHandler = context.deserialize(handler, EventHandlerSpecification.class);
  }

  return new DefaultTwillSpecification(name, runnables, orders, placementPolicies, eventHandler);
}
 
Example 5
static List<String> toStringList(JsonElement stringArr) {
    if (stringArr == null) {
        return Collections.EMPTY_LIST;
    } else if (stringArr.isJsonPrimitive()) {
        return Collections.singletonList(stringArr.getAsString());
    } else if (stringArr.isJsonArray()) {
        List<String> ret = new ArrayList<>();
        for (JsonElement el : ((JsonArray)stringArr)) {
            if (! el.isJsonNull()) {
                ret.add(el.getAsJsonPrimitive().getAsString());
            }
        }
        return ret;
    } else {
        throw new IllegalArgumentException("Didn't expect json object here:" + stringArr);
    }
}
 
Example 6
Source Project: The-5zig-Mod   File: ConfigNew.java    License: MIT License 6 votes vote down vote up
/**
 * Tries to load & parse the configuration from a json string.
 *
 * @param json the json string of the config.
 */
private void load(String json) {
	if (root != null) {
		throw new IllegalStateException("Config already loaded!");
	}

	JsonParser parser = new JsonParser();
	JsonElement parse = parser.parse(json);
	if (parse == null || parse.isJsonNull())
		throw new RuntimeException("Config not found!");

	root = parse.getAsJsonObject();

	for (ConfigItem item : items.values()) {
		try {
			item.deserialize(root);
		} catch (Exception e) {
			The5zigMod.logger.debug("Error deserializing item " + item, e);
			item.reset();
		}
	}
	The5zigMod.logger.debug("Loaded {} config items!", items.size());
}
 
Example 7
Source Project: i18n-editor   File: Resources.java    License: MIT License 5 votes vote down vote up
private static void fromJson(String key, JsonElement elem, Map<String,String> content) {
	if (elem.isJsonObject()) {
		elem.getAsJsonObject().entrySet().forEach(entry -> {
			String newKey = key == null ? entry.getKey() : ResourceKeys.create(key, entry.getKey());
			fromJson(newKey, entry.getValue(), content);
		});
	} else if (elem.isJsonPrimitive()) {
		content.put(key, StringEscapeUtils.unescapeJava(elem.getAsString()));
	} else if (elem.isJsonNull()) {
		content.put(key, "");
	} else {
		throw new IllegalArgumentException("Found invalid json element.");
	}
}
 
Example 8
Source Project: wasindoor   File: DzdpNet.java    License: Apache License 2.0 5 votes vote down vote up
public BusinessesDetail getBussniss(String bussnissId) throws Exception {

		Map<String, String> map = new HashMap<String, String>();
		map.put("business_ids", bussnissId);

		String url = getRequestUrl(Configuration.get_businesses_url, map);

		JsonElement root = parser.parse(this.getHttpServerResponse(url));

		if (root.isJsonObject()) {
			JsonObject rootobj = root.getAsJsonObject();
			JsonElement businesses = rootobj.get("businesses");
			// []
			if (businesses.isJsonNull())
				return new BusinessesDetail();
			if (businesses.isJsonArray()) {
				List<BusinessesDetail> result = gson.fromJson(businesses,
						new TypeToken<List<BusinessesDetail>>() {
						}.getType());

				if (result.size() > 0) {

					return result.get(0);
				}
			} else {
				return gson.fromJson(businesses,
						new TypeToken<BusinessesDetail>() {
						}.getType());
			}
		}

		return new BusinessesDetail();
	}
 
Example 9
Source Project: sonar-clojure   File: CloverageMetricParser.java    License: MIT License 5 votes vote down vote up
public static CoverageReport parse(SensorContext context, String json) {
    LOG.debug("Running CoverageReport parser");
    CoverageReport report = new CoverageReport();
    JsonParser parser = new JsonParser();
    JsonElement jsonTree = parser.parse(json);
    JsonObject jsonObject = jsonTree.getAsJsonObject();
    JsonObject r = jsonObject.get("coverage").getAsJsonObject();


    for (Map.Entry<String, JsonElement> e : r.entrySet()) {

        LOG.debug("Created new FileAnalysis: " + e.getKey());

        Optional<FileAnalysis> fileAnalysisOptional = findFileBySources(context, e.getKey());

        if (fileAnalysisOptional.isPresent()) {
            FileAnalysis fileAnalysis = fileAnalysisOptional.get();
            // first entry in csv is line number 0 which can be discarded
            int lineNumber = 0;
            for (JsonElement i : e.getValue().getAsJsonArray()) {
                if (lineNumber > 0 && !i.isJsonNull()) {
                    try {
                        fileAnalysis.addLine(lineNumber, i.getAsInt());
                    } catch (NumberFormatException n) {
                        fileAnalysis.addLine(lineNumber, 1);
                    }
                }
                lineNumber++;
            }
            report.addFile(fileAnalysis);
        } else {
            LOG.warn("Namespace: " + e.getKey() + " cannot be found.");
        }
    }

    return report;
}
 
Example 10
private String getTitleFromFill(Fill fill) {
  String title = "unknown";
  JsonElement customData = fill.getData();
  if (!(customData.isJsonNull())) {
    title = customData.getAsString();
  }
  return title;
}
 
Example 11
Source Project: paseto   File: OffsetDateTimeDeserializer.java    License: MIT License 5 votes vote down vote up
@Override
public OffsetDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
		throws JsonParseException {

	if (json.isJsonNull()) {
		return null;
	} else {
		return Token.DATETIME_FORMATTER.parse(json.getAsString());
	}
}
 
Example 12
Source Project: fingen   File: ReceiptDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
public FtsResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    FtsResponse response = new FtsResponse();
    if (!json.isJsonNull()) {
        JsonObject obj = json.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entries = obj.entrySet();//will return members of your object
        for (Map.Entry<String, JsonElement> entry: entries) {
            response.setDocument((Document) context.deserialize(entry.getValue(), Document.class));
        }
    }
    return response;
}
 
Example 13
private void updateJVMArgs(JsonObject settings)
{
	if (!settings.has("as3mxml"))
	{
		return;
	}
	JsonObject as3mxml = settings.get("as3mxml").getAsJsonObject();
	if (!as3mxml.has("asconfigc"))
	{
		return;
	}
	JsonObject asconfigc = as3mxml.get("asconfigc").getAsJsonObject();
	if (!asconfigc.has("jvmargs"))
	{
		return;
       }
       JsonElement jvmargsElement = asconfigc.get("jvmargs");
	String newJVMArgs = null;
       if(!jvmargsElement.isJsonNull())
       {
           newJVMArgs = asconfigc.get("jvmargs").getAsString();
       }
       if(jvmargs == null && newJVMArgs == null)
       {
           return;
       }
       if(jvmargs != null && jvmargs.equals(newJVMArgs))
       {
           return;
       }
       jvmargs = newJVMArgs;
       if(compilerShell != null)
       {
           compilerShell.dispose();
           compilerShell = null;
       }
}
 
Example 14
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id, JsonElement jsonElement) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		/** 防止提交空数据清空data */
		if (jsonElement.isJsonNull()) {
			throw new ExceptionNullData();
		}
		if (jsonElement.isJsonArray()) {
			throw new ExceptionArrayData();
		}
		if (jsonElement.isJsonPrimitive()) {
			throw new ExceptionPrimitiveData();
		}
		if (jsonElement.isJsonObject() && jsonElement.getAsJsonObject().entrySet().isEmpty()) {
			throw new ExceptionEmptyData();
		}
		ActionResult<Wo> result = new ActionResult<>();
		Business business = new Business(emc);
		Document document = emc.find(id, Document.class);
		if (null == document) {
			throw new ExceptionDocumentNotExists(id);
		}
		/** 先更新title和serial,再更新DataItem,因为旧的DataItem中也有title和serial数据. */
		this.updateTitleSerial(business, document, jsonElement);
		this.updateData(business, document, jsonElement);
		/** 在方法内进行了commit不需要再次进行commit */
		// emc.commit();
		Wo wo = new Wo();
		wo.setId(document.getId());
		result.setData(wo);
		
		ApplicationCache.notify( Document.class );
		
		return result;
	}
}
 
Example 15
Source Project: ja-micro   File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
public int extractInteger(JsonObject json, String name, int defaultValue) {
    if (json != null) {
        int dotIndex = name.indexOf('.');
        if (dotIndex > 0) {
            String baseName = name.substring(0, dotIndex);
            JsonElement childElement = json.get(baseName);
            return extractInteger((JsonObject) childElement, name.substring(dotIndex + 1), defaultValue);
        }
        JsonElement element = json.get(name);
        if (element != null && ! element.isJsonNull()) {
            return element.getAsInt();
        }
    }
    return defaultValue;
}
 
Example 16
Source Project: gson   File: TreeTypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override public T read(JsonReader in) throws IOException {
  if (deserializer == null) {
    return delegate().read(in);
  }
  JsonElement value = Streams.parse(in);
  if (value.isJsonNull()) {
    return null;
  }
  return deserializer.deserialize(value, typeToken.getType(), context);
}
 
Example 17
Source Project: cloudstack   File: Request.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<PortConfig> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonNull()) {
        return new ArrayList<PortConfig>();
    }
    List<PortConfig> pcs = new ArrayList<PortConfig>();
    JsonArray array = json.getAsJsonArray();
    Iterator<JsonElement> it = array.iterator();
    while (it.hasNext()) {
        JsonElement element = it.next();
        pcs.add(s_gson.fromJson(element, PortConfig.class));
    }
    return pcs;
}
 
Example 18
Source Project: secor   File: VectorColumnFiller.java    License: Apache License 2.0 5 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 {
        DecimalColumnVector vector = (DecimalColumnVector) vect;
        vector.vector[row].set(HiveDecimal.create(value.getAsString()));
    }
}
 
Example 19
public static <T> T extract(JsonElement jsonElement, String name, Class<T> cls, T defaultValue) {
	JsonElement element = extract(jsonElement, name);
	if (element == null || element.isJsonNull()) {
		return defaultValue;
	}
	return instance().fromJson(element, cls);
}
 
Example 20
Source Project: neodymium-library   File: JsonFileReader.java    License: MIT License 4 votes vote down vote up
public static List<Map<String, String>> readFile(InputStream inputStream)
{
    List<Map<String, String>> data = new LinkedList<>();
    try
    {
        BufferedInputStream bufferedStream = new BufferedInputStream(inputStream);
        InputStreamReader streamReader = new InputStreamReader(new BufferedInputStream(bufferedStream), Charset.forName("UTF-8"));
        JsonReader jsonReader = new JsonReader(streamReader);

        JsonArray asJsonArray = new JsonParser().parse(jsonReader).getAsJsonArray();

        for (int i = 0; i < asJsonArray.size(); i++)
        {
            JsonObject dataSet = asJsonArray.get(i).getAsJsonObject();
            Map<String, String> newDataSet = new HashMap<>();
            for (Entry<String, JsonElement> entry : dataSet.entrySet())
            {
                JsonElement element = entry.getValue();
                if (element.isJsonNull())
                {
                    newDataSet.put(entry.getKey(), null);
                }
                else if (element.isJsonArray() || element.isJsonObject())
                {
                    newDataSet.put(entry.getKey(), element.toString());
                }
                else
                {
                    newDataSet.put(entry.getKey(), element.getAsString());
                }
            }
            data.add(newDataSet);
        }

        jsonReader.close();
        streamReader.close();
        bufferedStream.close();

        return data;
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}