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

The following examples show how to use com.google.gson.JsonElement#toString() . 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: ColorDeserializer.java    From customstuff4 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Color deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
    if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber())
    {
        return new ColorImpl(json.getAsInt());
    } else if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString())
    {
        String s = json.getAsJsonPrimitive().getAsString();

        if (s.matches("[0-9a-fA-F]+"))
        {
            int col = (int) Long.parseLong(s, 16);
            return new ColorImpl(s.length() <= 6 ? 0xff000000 | col : col);
        } else
        {
            return new ColorImpl(registry.getColor(s));
        }
    }

    throw new JsonParseException("Invalid element for color: " + json.toString());
}
 
Example 2
Source File: JsonStringToJsonIntermediateConverter.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Parses primitive types
 * @param schema
 * @param value
 * @return
 * @throws DataConversionException
 */
private JsonElement parsePrimitiveType(JsonSchema schema, JsonElement value)
    throws DataConversionException {

  if ((schema.isType(NULL) || schema.isNullable()) && value.isJsonNull()) {
    return JsonNull.INSTANCE;
  }

  if ((schema.isType(NULL) && !value.isJsonNull()) || (!schema.isType(NULL) && value.isJsonNull())) {
    throw new DataConversionException(
        "Type mismatch for " + value.toString() + " of type " + schema.getDataTypes().toString());
  }

  if (schema.isType(FIXED)) {
    int expectedSize = schema.getSizeOfFixedData();
    if (value.getAsString().length() == expectedSize) {
      return value;
    } else {
      throw new DataConversionException(
          "Fixed type value is not same as defined value expected fieldsCount: " + expectedSize);
    }
  } else {
    return value;
  }
}
 
Example 3
Source File: ActionListWithSubjectForPage.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
protected ActionResult<List<Wo>> execute(HttpServletRequest request, EffectivePerson effectivePerson, Integer page,
		Integer count, JsonElement jsonElement) throws Exception {
	ActionResult<List<Wo>> result = new ActionResult<>();
	Wi wrapIn = null;
	Boolean check = true;

	try {
		wrapIn = this.convertToWrapIn(jsonElement, Wi.class);
		if( wrapIn.getShowSubReply() == null ){
			wrapIn.setShowSubReply(true);
		}
	} catch (Exception e) {
		check = false;
		Exception exception = new ExceptionReplyInfoProcess(e,"系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString());
		result.error(exception);
		logger.error(e, effectivePerson, request, null);
	}

	if (check) {
		String cacheKey = wrapIn.getSubjectId() + "#" + page + "#" + count + "#" + wrapIn.getShowSubReply();
		Element element = cache.get(cacheKey);

		if ((null != element) && (null != element.getObjectValue())) {
			ActionResult<List<Wo>> result_cache = (ActionResult<List<Wo>>) element.getObjectValue();
			result.setData(result_cache.getData());
			result.setCount(result_cache.getCount());
		} else {
			result = getReplyQueryResult( wrapIn, request, effectivePerson, page, count );
			cache.put(new Element(cacheKey, result));
		}
	}
	return result;
}
 
Example 4
Source File: LuaJsonElement.java    From Lukkit with MIT License 5 votes vote down vote up
private LuaValue getValueFromElement(JsonElement element) {
    if (element.isJsonArray() || element.isJsonObject()) {
        return this.getTableFromElement(element);
    } else if (element.isJsonNull()) {
        return LuaValue.NIL;
    } else if (element.isJsonPrimitive()) {
        JsonPrimitive primitiveValue = element.getAsJsonPrimitive();

        if (primitiveValue.isBoolean()) {
            return LuaValue.valueOf(primitiveValue.getAsBoolean());
        } else if (primitiveValue.isString()) {
            return LuaValue.valueOf(primitiveValue.getAsString());
        } else if (primitiveValue.isNumber()) {
            Number numberValue = primitiveValue.getAsNumber();

            if (numberValue instanceof Double)       return LuaValue.valueOf(numberValue.doubleValue());
            else if (numberValue instanceof Integer) return LuaValue.valueOf(numberValue.intValue());
            else if (numberValue instanceof Short)   return LuaValue.valueOf(numberValue.shortValue());
            else if (numberValue instanceof Long)    return LuaValue.valueOf(numberValue.longValue());
            else if (numberValue instanceof Float)   return LuaValue.valueOf(numberValue.floatValue());
            else if (numberValue instanceof Byte)    return LuaValue.valueOf(numberValue.byteValue());
        }
    } else {
        LuaError error = new LuaError("A LuaJsonElement object was passed an unsupported value other than that supported by LuaJ. Value: " + element.toString());
        LuaEnvironment.addError(error);
        error.printStackTrace();
    }

    return LuaValue.NIL;
}
 
Example 5
Source File: ServerResponsesFactory.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
public static DeviceNotification createNotificationForDevice(DeviceVO device, String notificationName) {
    DeviceNotification notification = new DeviceNotification();
    notification.setId(Math.abs(new Random().nextInt())); // TODO: remove this when id generation will be moved to backend
    notification.setNotification(notificationName);
    notification.setDeviceId(device.getDeviceId());
    Gson gson = GsonFactory.createGson(DEVICE_PUBLISHED);
    JsonElement deviceAsJson = gson.toJsonTree(device);
    JsonStringWrapper wrapperOverDevice = new JsonStringWrapper(deviceAsJson.toString());
    notification.setParameters(wrapperOverDevice);
    return notification;
}
 
Example 6
Source File: JsonFunctions.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override public T apply(JsonElement input) {
    if (input == null) return null;
    String jsonString = input.toString();
    Object rawElement = JsonPath.read(jsonString, path);
    return (T) rawElement;
}
 
Example 7
Source File: GsonParser.java    From QuickDevFramework with Apache License 2.0 5 votes vote down vote up
@Override
public JSONObject deserialize(JsonElement json, Type typeOfT,
                              JsonDeserializationContext context) throws JsonParseException {
    try {
        return new JSONObject(json.toString());
    } catch (JSONException e) {
        Log.w(TAG, "err, string = " + json.toString());
    }
    return null;
}
 
Example 8
Source File: JsonUtil.java    From java-trader with Apache License 2.0 5 votes vote down vote up
public static String json2str(JsonElement json, Boolean pretty) {
   try {
       StringWriter stringWriter = new StringWriter(1024);
        JsonWriter jsonWriter = new JsonWriter(stringWriter);
        if ( pretty!=null && pretty ) {
            jsonWriter.setIndent("  ");
        }
        jsonWriter.setLenient(true);
        Streams.write(json, jsonWriter);
        return stringWriter.toString();
   }catch(Throwable t) {
       return json.toString();
   }
}
 
Example 9
Source File: JsonUtils.java    From twill with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a String representation of the given property.
 */
public static String getAsString(JsonObject json, String property) {
  JsonElement jsonElement = json.get(property);
  if (jsonElement == null || jsonElement.isJsonNull()) {
    return null;
  }
  if (jsonElement.isJsonPrimitive()) {
    return jsonElement.getAsString();
  }
  return jsonElement.toString();
}
 
Example 10
Source File: GetArrayEntryService.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public @NotNull Map<String, String> execute(@NotNull GetArrayEntryInput input) {
    List<RuntimeException> validationErrs = this.validator.validate(input);
    if (!validationErrs.isEmpty()) {
        throw validationErrs.get(0);
    }

    int index = input.getIndex() < 0 ? input.getArray().size() + input.getIndex() : input.getIndex();
    JsonElement arrayEntry = input.getArray().get(index);

    String returnResult = arrayEntry.toString();
    return OutputUtilities.getSuccessResultsMap(returnResult);
}
 
Example 11
Source File: ExceptionWrapInConvert.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public ExceptionWrapInConvert( Throwable e, JsonElement jsonElement) {
	super( "系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString(), e);
}
 
Example 12
Source File: ExceptionWrapInConvert.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public ExceptionWrapInConvert( Throwable e, JsonElement jsonElement) {
	super( "系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString(), e);
}
 
Example 13
Source File: ActionListPrevWithFilter.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
protected ActionResult<List<WoOkrWorkBaseInfo>> execute(HttpServletRequest request, EffectivePerson effectivePerson,
		String id, Integer count, JsonElement jsonElement) throws Exception {
	ActionResult<List<WoOkrWorkBaseInfo>> result = new ActionResult<>();
	String sequenceField = null;
	EqualsTerms equalsMap = new EqualsTerms();
	NotEqualsTerms notEqualsMap = new NotEqualsTerms();
	InTerms insMap = new InTerms();
	NotInTerms notInsMap = new NotInTerms();
	MemberTerms membersMap = new MemberTerms();
	NotMemberTerms notMembersMap = new NotMemberTerms();
	LikeTerms likesMap = new LikeTerms();
	Wi wrapIn = null;
	Boolean check = true;

	try {
		wrapIn = this.convertToWrapIn(jsonElement, Wi.class);
	} catch (Exception e) {
		check = false;
		Exception exception = new ExceptionWorkBaseInfoProcess(e,
				"系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString());
		result.error(exception);
		logger.error(e, effectivePerson, request, null);
	}

	if (check) {
		if (wrapIn.getFilterLikeContent() != null && !wrapIn.getFilterLikeContent().isEmpty()) {
			likesMap.put("title", wrapIn.getFilterLikeContent());
			likesMap.put("shortWorkDetail", wrapIn.getFilterLikeContent());
			likesMap.put("centerTitle", wrapIn.getFilterLikeContent());
			likesMap.put("creatorIdentity", wrapIn.getFilterLikeContent());
			likesMap.put("workType", wrapIn.getFilterLikeContent());
			likesMap.put("responsibilityEmployeeName", wrapIn.getFilterLikeContent());
			likesMap.put("workProcessStatus", wrapIn.getFilterLikeContent());
		}
	}
	if (check) {
		sequenceField = wrapIn.getSequenceField();
		try {
			result = this.standardListNext(WoOkrWorkBaseInfo.copier, id, count, sequenceField, equalsMap,
					notEqualsMap, likesMap, insMap, notInsMap, membersMap, notMembersMap, null, false,
					wrapIn.getOrder());
		} catch (Throwable th) {
			th.printStackTrace();
			result.error(th);
		}
	}
	return result;
}
 
Example 14
Source File: ExceptionWrapInConvert.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public ExceptionWrapInConvert( Throwable e, JsonElement jsonElement) {
	super( "系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString(), e);
}
 
Example 15
Source File: ExceptionWrapInConvert.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public ExceptionWrapInConvert( Throwable e, JsonElement jsonElement) {
	super( "系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString(), e);
}
 
Example 16
Source File: ExceptionWrapInConvert.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public ExceptionWrapInConvert( Throwable e, JsonElement jsonElement) {
	super( "系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString(), e);
}
 
Example 17
Source File: ExceptionWrapInConvert.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public ExceptionWrapInConvert( Throwable e, JsonElement jsonElement) {
	super( "系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString(), e);
}
 
Example 18
Source File: FixedChatSerializer.java    From Carbon-2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public IChatBaseComponent deserialize(JsonElement element, Type type, JsonDeserializationContext ctx) throws JsonParseException {
    if (element.isJsonPrimitive()) {
        return new ChatComponentText(element.getAsString());
    } else if (!element.isJsonObject()) {
        if (element.isJsonArray()) {
            JsonArray jsonArray = element.getAsJsonArray();
            IChatBaseComponent chatcomp = null;
            for (JsonElement jsonElement : jsonArray) {
                IChatBaseComponent innerchatcomp = deserialize(jsonElement, jsonElement.getClass(), ctx);
                if (chatcomp == null) {
                    chatcomp = innerchatcomp;
                } else {
                    chatcomp.addSibling(innerchatcomp);
                }
            }
            return chatcomp;
        } else {
            throw new JsonParseException("Don\'t know how to turn " + element.toString() + " into a Component");
        }
    } else {
        JsonObject jsonobject = element.getAsJsonObject();
        IChatBaseComponent resultComp;
        if (jsonobject.has("text")) {
            resultComp = new ChatComponentText(jsonobject.get("text").getAsString());
        } else if (jsonobject.has("translate")) {
            String translate = jsonobject.get("translate").getAsString();
            if (jsonobject.has("with")) {
                JsonArray withJsonArray = jsonobject.getAsJsonArray("with");
                Object[] array = new Object[withJsonArray.size()];

                for (int i = 0; i < array.length; ++i) {
                    array[i] = deserialize(withJsonArray.get(i), type, ctx);
                    if (array[i] instanceof ChatComponentText) {
                        ChatComponentText compText = (ChatComponentText) array[i];
                        if (compText.getChatModifier().g() && compText.a().isEmpty()) {
                            array[i] = compText.g();
                        }
                    }
                }

                resultComp = new ChatMessage(translate, array);
            } else {
                resultComp = new ChatMessage(translate);
            }
        } else if (jsonobject.has("score")) {
            JsonObject scoreJsonObject = jsonobject.getAsJsonObject("score");
            if (!scoreJsonObject.has("name") || !scoreJsonObject.has("objective")) {
                throw new JsonParseException("A score component needs a least a name and an objective");
            }

            resultComp = new ChatComponentScore(JsonHelper.getString(scoreJsonObject, "name"), JsonHelper.getString(scoreJsonObject, "objective"));
            if (scoreJsonObject.has("value")) {
                ((ChatComponentScore) resultComp).b(JsonHelper.getString(scoreJsonObject, "value"));
            }
        } else {
            if (!jsonobject.has("selector")) {
                throw new JsonParseException("Don\'t know how to turn " + element.toString() + " into a Component");
            }

            resultComp = new ChatComponentSelector(JsonHelper.getString(jsonobject, "selector"));
        }

        if (jsonobject.has("extra")) {
            JsonArray entryJsonArray = jsonobject.getAsJsonArray("extra");
            if (entryJsonArray.size() <= 0) {
                throw new JsonParseException("Unexpected empty array of components");
            }
            for (int i = 0; i < entryJsonArray.size(); ++i) {
                resultComp.addSibling(deserialize(entryJsonArray.get(i), type, ctx));
            }
        }

        resultComp.setChatModifier((ChatModifier) ctx.deserialize(element, ChatModifier.class));
        return resultComp;
    }
}
 
Example 19
Source File: ExceptionWrapInConvert.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public ExceptionWrapInConvert( Throwable e, JsonElement jsonElement) {
	super( "系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString(), e);
}
 
Example 20
Source File: ExceptionWrapInConvert.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public ExceptionWrapInConvert( Throwable e, JsonElement jsonElement) {
	super( "系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString(), e);
}