com.alibaba.fastjson.JSONException Java Examples

The following examples show how to use com.alibaba.fastjson.JSONException. 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: JSONSerializer.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public final void writeWithFieldName(Object object, Object fieldName, Type fieldType, int fieldFeatures) {
    try {
        if (object == null) {
            out.writeNull();
            return;
        }

        Class<?> clazz = object.getClass();

        ObjectSerializer writer = getObjectWriter(clazz);

        writer.write(this, object, fieldName, fieldType, fieldFeatures);
    } catch (IOException e) {
        throw new JSONException(e.getMessage(), e);
    }
}
 
Example #2
Source File: WXWebView.java    From CrazyDaily with Apache License 2.0 6 votes vote down vote up
@Override
public void postMessage(Object msg) {
    if (getWebView() == null) {
        return;
    }

    try {
        JSONObject initData = new JSONObject();
        initData.put("type", "message");
        initData.put("data", msg);
        initData.put("origin", mOrigin);
        evaluateJS("javascript:(function () {"
                + "var initData = " + initData.toString() + ";"
                + "try {"
                + "var event = new MessageEvent('message', initData);"
                + "window.dispatchEvent(event);"
                + "} catch (e) {}"
                + "})();");
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}
 
Example #3
Source File: JSONReaderScanner.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public JSONReaderScanner(Reader reader, int features){
    super(features);
    this.reader = reader;

    buf = BUF_LOCAL.get();
    if (buf != null) {
        BUF_LOCAL.set(null);
    }

    if (buf == null) {
        buf = new char[1024 * 16];
    }

    try {
        bufLength = reader.read(buf);
    } catch (IOException e) {
        throw new JSONException(e.getMessage(), e);
    }

    bp = -1;

    next();
    if (ch == 65279) { // utf8 bom
        next();
    }
}
 
Example #4
Source File: JsonFieldRender.java    From gecco with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked" })
public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) {
	Map<String, Object> fieldMap = new HashMap<String, Object>();
	Set<Field> jsonPathFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(JSONPath.class));
	String jsonStr = response.getContent();
	jsonStr = jsonp2Json(jsonStr);
	if (jsonStr == null) {
		return;
	}
	try {
		Object json = JSON.parse(jsonStr);
		for (Field field : jsonPathFields) {
			Object value = injectJsonField(request, field, json);
			if(value != null) {
				fieldMap.put(field.getName(), value);
			}
		}
	} catch(JSONException ex) {
		//throw new RenderException(ex.getMessage(), bean.getClass());
		RenderException.log("json parse error : " + request.getUrl(), bean.getClass(), ex);
	}
	beanMap.putAll(fieldMap);
}
 
Example #5
Source File: TypeUtils.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public static Character castToChar(Object value){
    if(value == null){
        return null;
    }
    if(value instanceof Character){
        return (Character) value;
    }
    if(value instanceof String){
        String strVal = (String) value;
        if(strVal.length() == 0){
            return null;
        }
        if(strVal.length() != 1){
            throw new JSONException("can not cast to char, value : " + value);
        }
        return strVal.charAt(0);
    }
    throw new JSONException("can not cast to char, value : " + value);
}
 
Example #6
Source File: JsonDBUtil.java    From paraflow with Apache License 2.0 6 votes vote down vote up
public static JSONArray rSToJson(ResultSet rs) throws SQLException, JSONException
{
    JSONArray array = new JSONArray();
    ResultSetMetaData metaData = rs.getMetaData();
    int columnCount = metaData.getColumnCount();
    while (rs.next()) {
        JSONObject jsonObj = new JSONObject();
        for (int i = 1; i <= columnCount; i++) {
            String columnName = metaData.getColumnLabel(i);
            String value = rs.getString(columnName);
            jsonObj.put(columnName, value);
        }
        array.add(jsonObj);
    }
    return array;
}
 
Example #7
Source File: JsonAction.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
@Override
public Status act(UpstreamJob job, byte[] bytes) {
    try {
        JSONObject jsonObject = JSON.parseObject(StringUtils.newString(bytes));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("send content {}", JsonUtils.toJsonString(jsonObject));
        }
        if(jsonObject == null) {
            return Status.FINISH;
        }

        job.setData(jsonObject);
        return Status.CONTINUE;
    } catch (JSONException e) {
        MetricUtils.qpsAndFilterMetric(job, MetricUtils.ConsumeResult.INVALID);
        LogUtils.logErrorInfo("Json_error", String.format("parse data to JSON failed. job=%s", job.info()));
        LOGGER.debug(String.format("parse data to JSON failed. job=%s, error detail:", job.info()), e);
        return Status.FAIL;
    }
}
 
Example #8
Source File: TypeUtils.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public static Float castToFloat(Object value){
    if(value == null){
        return null;
    }
    if(value instanceof Number){
        return ((Number) value).floatValue();
    }
    if(value instanceof String){
        String strVal = value.toString();
        if(strVal.length() == 0 //
                || "null".equals(strVal) //
                || "NULL".equals(strVal)){
            return null;
        }
        if(strVal.indexOf(',') != 0){
            strVal = strVal.replaceAll(",", "");
        }
        return Float.parseFloat(strVal);
    }
    throw new JSONException("can not cast to float, value : " + value);
}
 
Example #9
Source File: FastJsonSerializationTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void test_MediaContent_badStream() throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject(mediaContent);
    objectOutput.flushBuffer();

    byte[] byteArray = byteArrayOutputStream.toByteArray();
    for (int i = 0; i < byteArray.length; i++) {
        if(i%3 == 0) {
            byteArray[i] = (byte)~byteArray[i];
        }
    }
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
    
    try {
        ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
        @SuppressWarnings("unused") // local variable, convenient for debug
        Object read = deserialize.readObject();
        fail();
    } catch (JSONException expected) {
        System.out.println(expected);
    }
}
 
Example #10
Source File: SimpleHintParser.java    From tddl with Apache License 2.0 6 votes vote down vote up
public static RouteCondition convertHint2RouteCondition(String sql, Map<Integer, ParameterContext> parameterSettings) {
    String tddlHint = extractHint(sql, parameterSettings);
    if (StringUtils.isNotEmpty(tddlHint)) {
        try {
            JSONObject jsonObject = JSON.parseObject(tddlHint);
            String type = jsonObject.getString("type");
            if ("direct".equalsIgnoreCase(type)) {
                return decodeDirect(jsonObject);
            } else if ("condition".equalsIgnoreCase(type)) {
                return decodeCondition(jsonObject);
            } else {
                return decodeExtra(jsonObject);
            }
        } catch (JSONException e) {
            logger.error("convert tddl hint to RouteContion faild,check the hint string!", e);
            throw e;
        }

    }

    return null;
}
 
Example #11
Source File: DatabaseConnectController.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
private void setJsonTimeseries(JSONObject obj, String target,
    Pair<ZonedDateTime, ZonedDateTime> timeRange)
    throws JSONException {
  List<TimeValues> timeValues = databaseConnectService.querySeries(target, timeRange);
  logger.info("query size: {}", timeValues.size());
  JSONArray dataPoints = new JSONArray();
  for (TimeValues tv : timeValues) {
    long time = tv.getTime();
    Object value = tv.getValue();
    JSONArray jsonArray = new JSONArray();
    jsonArray.add(value);
    jsonArray.add(time);
    dataPoints.add(jsonArray);
  }
  obj.put("datapoints", dataPoints);
}
 
Example #12
Source File: FastJsonSerializationTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void test_MediaContent_badStream() throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject(mediaContent);
    objectOutput.flushBuffer();

    byte[] byteArray = byteArrayOutputStream.toByteArray();
    for (int i = 0; i < byteArray.length; i++) {
        if(i%3 == 0) {
            byteArray[i] = (byte)~byteArray[i];
        }
    }
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
    
    try {
        ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
        @SuppressWarnings("unused") // local variable, convenient for debug
        Object read = deserialize.readObject();
        fail();
    } catch (JSONException expected) {
        System.out.println(expected);
    }
}
 
Example #13
Source File: OkhttpApi.java    From evt4j with MIT License 6 votes vote down vote up
private void checkResponseError(@NotNull String body) throws ApiResponseException {
    boolean isArray = false;

    try {
        JSONArray.parseArray(body);
        isArray = true;
    } catch (JSONException ex) {
    }

    if (isArray) {
        return;
    }

    JSONObject res = JSONObject.parseObject(body);

    if (res.containsKey("error")) {
        throw new ApiResponseException(String.format("Response Error for '%s'", uri), res);
    }
}
 
Example #14
Source File: FastJsonSerializationTest.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
@Test
public void test_MediaContent_WithType_badStream() throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject(mediaContent);
    objectOutput.flushBuffer();

    byte[] byteArray = byteArrayOutputStream.toByteArray();
    for (int i = 0; i < byteArray.length; i++) {
        if(i%3 == 0) {
            byteArray[i] = (byte)~byteArray[i];
        }
    }
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
    
    try {
        ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
        @SuppressWarnings("unused") // local variable, convenient for debug
        Object read = deserialize.readObject(MediaContent.class);
        fail();
    } catch (JSONException expected) {
        System.out.println(expected);
    }
}
 
Example #15
Source File: FastJsonSerializationTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void test_MediaContent_WithType_badStream() throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject(mediaContent);
    objectOutput.flushBuffer();

    byte[] byteArray = byteArrayOutputStream.toByteArray();
    for (int i = 0; i < byteArray.length; i++) {
        if(i%3 == 0) {
            byteArray[i] = (byte)~byteArray[i];
        }
    }
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
    
    try {
        ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
        @SuppressWarnings("unused") // local variable, convenient for debug
        Object read = deserialize.readObject(MediaContent.class);
        fail();
    } catch (JSONException expected) {
        System.out.println(expected);
    }
}
 
Example #16
Source File: MdcGelfJsonMessageAssembler.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public GelfMessage createGelfMessage(LogEvent event) {//todo factory is better than overwriting.
    GelfMessage gelfMessage = super.createGelfMessage(event);
    if (event != null && event.getMessage() != null) {
        String originalMessage = event.getMessage().trim();
        if (originalMessage.startsWith("{")/* && originalMessage.endsWith("}")*/) {
            try {
                JSONObject fields = (JSONObject) JSON.parse(originalMessage);
                for (String key : fields.keySet()) {
                    gelfMessage.addField(key, fields.get(key) + "");
                }
            } catch (JSONException ignored) {
                //ignored because the log content is not a json string.
            }
        }
    }
    return gelfMessage;
}
 
Example #17
Source File: LogCollectService.java    From cicada with MIT License 6 votes vote down vote up
/**
 * 解析日志行.
 * 
 * @param lines 输入参数,从日志中读取到的原始采集数据
 * @param spanModels 输出参数,处理之后的SpanModel数据
 * @param annoModels 输出参数,处理之后的AnnotationModel数据
 */
private void analyze(final List<String> lines, //
    final List<SpanModel> spanModels, //
    final List<AnnotationModel> annoModels) {

  String message = null;
  for (final String line : lines) {
    try {
      // 清洗数据
      message = washer.wash(line);
      // 解json
      final List<Span> spans = JSON.parseObject(message, new TypeReference<List<Span>>() {});
      // 生成调用链数据的存储对象
      genTraceChainModel(spans, spanModels, annoModels);
    } catch (JSONException ex) {
      log.error("failed parse line {}, error {}", message, ex);
      continue;
    }
  }
}
 
Example #18
Source File: FastJsonProvider.java    From uavstack with Apache License 2.0 6 votes vote down vote up
/**
 * Method that JAX-RS container calls to deserialize given value.
 */
public Object readFrom(Class<Object> type, //
                       Type genericType, //
                       Annotation[] annotations, //
                       MediaType mediaType, //
                       MultivaluedMap<String, String> httpHeaders, //
                       InputStream entityStream) throws IOException, WebApplicationException {

    try {
        FastJsonConfig fastJsonConfig = locateConfigProvider(type, mediaType);

        return JSON.parseObject(entityStream, fastJsonConfig.getCharset(), genericType, fastJsonConfig.getFeatures());

    } catch (JSONException ex) {

        throw new WebApplicationException("JSON parse error: " + ex.getMessage(), ex);
    }
}
 
Example #19
Source File: TransactionDetail.java    From evt4j with MIT License 5 votes vote down vote up
private TransactionDetail(@NotNull JSONObject raw) throws JSONException {
    blockNum = raw.getInteger("block_num");
    packedTrx = raw.getString("packed_trx");
    id = raw.getString("id");
    compression = raw.getString("compression");
    JSONArray signaturesArray = raw.getJSONArray("signatures");

    for (int i = 0; i < signaturesArray.size(); i++) {
        signatures.add(Signature.of((String) signaturesArray.get(i)));
    }

    transaction = raw.getJSONObject("transaction");
    blockId = raw.getString("block_id");
}
 
Example #20
Source File: Jsoner.java    From ICERest with Apache License 2.0 5 votes vote down vote up
public static <T> T toObject(String json, Class<T> clazz) {
    try {
        if (deserializerFeatures != null) {
            return JSON.parseObject(json, clazz, deserializerFeatures);
        } else {
            return JSON.parseObject(json, clazz);
        }
    } catch (JSONException e) {
        throw new JsonException("Could not cast \"" + json + "\" to " + clazz.getName(), e);
    }
}
 
Example #21
Source File: AnnotationRepository.java    From cicada with MIT License 5 votes vote down vote up
/**
 * 根据traceId和spanId获取annotationModel列表.
 */
public List<AnnotationModel> getSpanAnnotations(final String traceId, final String spanId) {
  // 声明SearchRequestBuilder实例
  final String indice = getDefaultIndice();
  final SearchRequestBuilder builder = client.prepareSearch(indice);
  builder.setTypes(props.getEsTypeName());

  // 设置查询条件
  final BoolQueryBuilder query = new BoolQueryBuilder();
  query.must(QueryBuilders.termQuery("traceId", traceId)) //
      .must(QueryBuilders.termQuery("spanId", spanId));

  // 执行查询
  final SearchResponse response = builder.setQuery(query).execute().actionGet();

  // 处理返回结果
  final List<AnnotationModel> annos = new LinkedList<AnnotationModel>();
  for (final SearchHit hit : response.getHits().hits()) {
    final String docStr = hit.getSourceAsString();
    try {
      final AnnotationModel model = JSON.parseObject(docStr, AnnotationModel.class);
      annos.add(model);
    } catch (JSONException ex) {
      log.error("failed load data {} to AnnotationModel, error {}", docStr, ex);
      continue;
    }
  }

  return annos;
}
 
Example #22
Source File: JSONSerializer.java    From letv with Apache License 2.0 5 votes vote down vote up
public final void writeWithFieldName(Object object, Object fieldName, Type fieldType) {
    if (object == null) {
        try {
            this.out.writeNull();
            return;
        } catch (IOException e) {
            throw new JSONException(e.getMessage(), e);
        }
    }
    getObjectWriter(object.getClass()).write(this, object, fieldName, fieldType);
}
 
Example #23
Source File: JSONSerializer.java    From letv with Apache License 2.0 5 votes vote down vote up
public final void write(Object object) {
    if (object == null) {
        this.out.writeNull();
        return;
    }
    try {
        getObjectWriter(object.getClass()).write(this, object, null, null);
    } catch (IOException e) {
        throw new JSONException(e.getMessage(), e);
    }
}
 
Example #24
Source File: OldHintParser.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
private static void decodeSpecifyInfo(RouteCondition condition, Map<String, Object> hints) throws JSONException {
    String skip = (String) hints.get("skip");
    String max = (String) hints.get("max");
    String orderby = (String) hints.get("orderby");
    if (skip != null || max != null || orderby != null) {
        throw new SqlParserException("不支持的tddl3.1.x的hint特殊参数");
    }
}
 
Example #25
Source File: UWXNavigatorModule2.java    From ucar-weex-core with Apache License 2.0 5 votes vote down vote up
@JSMethod
public void setNavBarHidden(String param, final String callback) {
    String message = MSG_FAILED;
    try {
        JSONObject jsObj = JSON.parseObject(param);
        int visibility = jsObj.getInteger(Constants.Name.NAV_BAR_VISIBILITY);
        boolean success = changeVisibilityOfActionBar(mWXSDKInstance.getContext(), visibility);
        if (success) {
            message = MSG_SUCCESS;
        }
    } catch (JSONException e) {
        WXLogUtils.e(TAG, WXLogUtils.getStackTrace(e));
    }
    WXBridgeManager.getInstance().callback(mWXSDKInstance.getInstanceId(), callback, message);
}
 
Example #26
Source File: SOAResParseUtil.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 获取返回的JSON对象
 *
 * @param result
 * @return
 * @author xuxiao
 * @created 2014年5月7日 下午5:59:58
 */
public static JSONObject getJsonObj(final String result) {
    try {
        return JSON.parseObject(result);
    } catch (final JSONException e) {
        LOGGER.error("解析SOA返回JSON结果错误!", e);
        return null;
    }
}
 
Example #27
Source File: JsonKit.java    From zbus-server with MIT License 5 votes vote down vote up
public static <T> T parseObject(String jsonString, Class<T> clazz) {
	try{
		return JSON.parseObject(jsonString, clazz);
	} catch (JSONException e) {
		jsonString = jsonString.replace("@type", "@typeUnknown");
		return JSON.parseObject(jsonString, clazz);
	}
}
 
Example #28
Source File: UWXResManager.java    From ucar-weex-core with Apache License 2.0 5 votes vote down vote up
private void iniWXInfo() {
    String packageJson = preferences.getString("wx_res_info", "");
    try {
        packageInfos = JSON.parseArray(packageJson, WXPackageInfo.class);
        this.lastPackageInfo = !ArrayUtils.isEmpty(packageInfos) ? packageInfos.get(0) : null;
    } catch (JSONException e) {
        packageInfos = null;
        UWLog.e(TAG, e.getMessage());
    }
}
 
Example #29
Source File: MyFieldSerializer.java    From dpCms with Apache License 2.0 5 votes vote down vote up
public Object getPropertyValue(Object object) throws Exception {
    try {
        return fieldInfo.get(object);
    } catch (Exception ex) {
        throw new JSONException("get property error。 " + fieldInfo.gerQualifiedName(), ex);
    }
}
 
Example #30
Source File: JSONLexerBase.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public final void scanTrue() {
    if (ch != 't') {
        throw new JSONException("error parse true");
    }
    next();

    if (ch != 'r') {
        throw new JSONException("error parse true");
    }
    next();

    if (ch != 'u') {
        throw new JSONException("error parse true");
    }
    next();

    if (ch != 'e') {
        throw new JSONException("error parse true");
    }
    next();

    if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI
            || ch == '\f' || ch == '\b' || ch == ':' || ch == '/') {
        token = JSONToken.TRUE;
    } else {
        throw new JSONException("scan true error");
    }
}