Java Code Examples for com.alibaba.fastjson.JSONException

The following examples show how to use com.alibaba.fastjson.JSONException. These examples are extracted from open source projects. 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 Project: uavstack   Source File: TypeUtils.java    License: 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 2
Source Project: DDMQ   Source File: JsonAction.java    License: 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 3
Source Project: dubbox   Source File: FastJsonSerializationTest.java    License: 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 4
Source Project: incubator-iotdb   Source File: DatabaseConnectController.java    License: 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 5
Source Project: xian   Source File: MdcGelfJsonMessageAssembler.java    License: 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 6
Source Project: uavstack   Source File: JSONSerializer.java    License: 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 7
Source Project: cicada   Source File: LogCollectService.java    License: 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 8
Source Project: dubbox   Source File: FastJsonSerializationTest.java    License: 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 9
Source Project: evt4j   Source File: OkhttpApi.java    License: 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 10
Source Project: tddl   Source File: SimpleHintParser.java    License: 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 Project: CrazyDaily   Source File: WXWebView.java    License: 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 12
Source Project: paraflow   Source File: JsonDBUtil.java    License: 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 13
Source Project: uavstack   Source File: TypeUtils.java    License: 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 14
Source Project: dubbox   Source File: FastJsonSerializationTest.java    License: 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 15
Source Project: dubbox-hystrix   Source File: FastJsonSerializationTest.java    License: 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 Project: uavstack   Source File: FastJsonProvider.java    License: 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 17
Source Project: gecco   Source File: JsonFieldRender.java    License: 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 18
Source Project: uavstack   Source File: JSONReaderScanner.java    License: 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 19
Source Project: renrenpay-android   Source File: SocketService.java    License: Apache License 2.0 5 votes vote down vote up
public void getOrder(String orderId) {
    JSONObject object = new JSONObject();
    try {
        object.put("service", "RECEIVEORDER");
        object.put("orderNo", orderId);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    sendMsg(object.toString());
}
 
Example 20
Source Project: ICERest   Source File: Jsoner.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> T toObject(String json, Class<T> clazz, ParseProcess processor) {
    try {
        if (deserializerFeatures != null) {
            return JSON.parseObject(json, clazz, processor, deserializerFeatures);
        } else {
            return JSON.parseObject(json, clazz, processor);
        }
    } catch (JSONException e) {
        throw new JsonException("Could not cast \"" + json + "\" to " + clazz.getName(), e);
    }
}
 
Example 21
Source Project: tddl   Source File: SimpleHintParser.java    License: Apache License 2.0 5 votes vote down vote up
private static ExtraCmdRouteCondition decodeExtra(JSONObject jsonObject) throws JSONException {
    ExtraCmdRouteCondition rc = new ExtraCmdRouteCondition();
    String extraCmd = containsKvNotBlank(jsonObject, EXTRACMD);
    if (StringUtils.isNotEmpty(extraCmd)) {
        JSONObject extraCmds = JSON.parseObject(extraCmd);
        for (Map.Entry<String, Object> entry : extraCmds.entrySet()) {
            rc.getExtraCmds().put(StringUtils.upperCase(entry.getKey()), entry.getValue());
        }
    }
    return rc;
}
 
Example 22
Source Project: tddl   Source File: SimpleHintParser.java    License: Apache License 2.0 5 votes vote down vote up
private static void decodeExtra(RouteCondition rc, JSONObject jsonObject) throws JSONException {
    String extraCmd = containsKvNotBlank(jsonObject, EXTRACMD);
    if (StringUtils.isNotEmpty(extraCmd)) {
        JSONObject extraCmds = JSON.parseObject(extraCmd);
        rc.getExtraCmds().putAll(extraCmds);
    }
}
 
Example 23
Source Project: NIM_Android_UIKit   Source File: AnnouncementHelper.java    License: MIT License 5 votes vote down vote up
public static List<Announcement> getAnnouncements(String teamId, String announce, int limit) {
    if (TextUtils.isEmpty(announce)) {
        return null;
    }

    List<Announcement> announcements = new ArrayList<>();
    try {
        int count = 0;
        JSONArray jsonArray = JSONArray.parseArray(announce);
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject json = jsonArray.getJSONObject(i);
            String id = json.getString(JSON_KEY_ID);
            String creator = json.getString(JSON_KEY_CREATOR);
            String title = json.getString(JSON_KEY_TITLE);
            long time = json.getLongValue(JSON_KEY_TIME);
            String content = json.getString(JSON_KEY_CONTENT);

            announcements.add(new Announcement(id, teamId, creator, title, time, content));

            if (++count >= limit) {
                break;
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return announcements;
}
 
Example 24
Source Project: fabric-net-server   Source File: IntermediateChaincodeID.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 判断字符串类型
 *
 * @param str 字符串
 *
 * @return 0-string;1-JsonObject;2、JsonArray
 */
private static int isJSONValid(String str) {
    try {
        JSONObject.parseObject(str);
        return 1;
    } catch (JSONException ex) {
        try {
            JSONObject.parseArray(str);
            return 2;
        } catch (JSONException ex1) {
            return 0;
        }
    }
}
 
Example 25
Source Project: Tpay   Source File: StringRequestGet.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
        return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}
 
Example 26
Source Project: Tpay   Source File: FastJsonRequest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Response<BaseMsg> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
        return Response.success(
                JSON.parseObject(jsonString, BaseMsg.class), HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}
 
Example 27
Source Project: uavstack   Source File: ClobSeriliazer.java    License: Apache License 2.0 5 votes vote down vote up
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
    try {
        if (object == null) {
            serializer.writeNull();
            return;
        }
        
        Clob clob = (Clob) object;
        Reader reader = clob.getCharacterStream();

        StringBuilder buf = new StringBuilder();
        
        try {
            char[] chars = new char[2048];
            for (;;) {
                int len = reader.read(chars, 0, chars.length);
                if (len < 0) {
                    break;
                }
                buf.append(chars, 0, len);
            }
        } catch(Exception ex) {
            throw new JSONException("read string from reader error", ex);
        }
        
        String text = buf.toString();
        reader.close();
        serializer.write(text);
    } catch (SQLException e) {
        throw new IOException("write clob error", e);
    }
}
 
Example 28
Source Project: xian   Source File: TokenRequest_json.java    License: Apache License 2.0 5 votes vote down vote up
public static TokenRequest_json create(FullHttpRequest httpRequest) {
    String body = httpRequest.content().toString(CharsetUtil.UTF_8);
    try {
        return JSON.parseObject(body).toJavaObject(TokenRequest_json.class);
    } catch (JSONException e) {
        throw new IllegalArgumentException(String.format("tokenRequest请求的jsonBody格式不合法:%s", body), e);
    }
}
 
Example 29
Source Project: xian   Source File: ZkPathManager.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isServiceNode(ChildData zNode) {
    String path = zNode.getPath();
    LOG.debug("正在检查节点路径:   " + path);
    LOG.debug("服务注册路径:   " + getNodeBasePath());
    if (!path.startsWith(getNodeBasePath()) || path.equals(getNodeBasePath())) {
        return false;
    }
    String name = path.substring((getNodeBasePath() + "/").length());
    String[] names = name.split("/");
    if (names.length != 2) {
        return false;
    }
    /*if (!SystemEnum.isServiceNodeName(names[0])) {
        todo 由于去掉了systemEnum类,我们在watch到zk外部服务注册事件之前,根本不知道到底有哪些application
        return false;
    }*/
    String zNodeDataStr = new String(zNode.getData());
    JSONObject zNodeData;
    try {
        zNodeData = JSON.parseObject(zNodeDataStr);
    } catch (JSONException notJsonString) {
        LOG.debug(String.format("节点%s的data是%s,它不是我们要找的那个服务节点,排除掉!  这是我期待结果之一,不打印堆栈", path, zNodeDataStr));
        return false;
    }
    try {
        if (zNodeData.getJSONObject("payload") == null) {
            LOG.debug(String.format("节点=%s,内容=%s,其内缺少payload属性,它不是我们预期的服务节点!", path, zNodeDataStr));
            return false;
        }
    } catch (JSONException payloadIsNotJsonString) {
        LOG.info(String.format("节点%s的data=%s,其内的payload属性是不是json格式,肯定是有非预期的节点混入,这里排除之", path, zNodeDataStr));
        return false;
    }
    return true;
}
 
Example 30
Source Project: uavstack   Source File: JSONSerializer.java    License: Apache License 2.0 5 votes vote down vote up
public final void write(Object object) {
    if (object == null) {
        out.writeNull();
        return;
    }

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

    try {
        writer.write(this, object, null, null, 0);
    } catch (IOException e) {
        throw new JSONException(e.getMessage(), e);
    }
}