Java Code Examples for com.alibaba.fastjson.JSON#toJSONBytes()

The following examples show how to use com.alibaba.fastjson.JSON#toJSONBytes() . 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
@Override
public byte[] serialize(Object object, ClassLoader classLoader) throws SerializeException {
    ClassLoader swap = Thread.currentThread().getContextClassLoader();
    try {
        if (classLoader != null) {
            Thread.currentThread().setContextClassLoader(classLoader);
        }
        return JSON.toJSONBytes(object, features);
    } catch (Throwable t) {
        // may produce sof exception
        throw new SerializeException("[Error-1001]-json-serialize-error", t);
    } finally {
        if (classLoader != null) {
            Thread.currentThread().setContextClassLoader(swap);
        }
    }
}
 
Example 2
Source Project: hermes   File: JsonPerfTest.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < 1000; i++) {
		sb.append("x");
	}
	String str = sb.toString();

	JSON.toJSONString(str);

	long start = System.currentTimeMillis();
	for (int i = 0; i < 10000; i++) {
		// JSON.toJSONString(str);
		 JSON.toJSONBytes(str);
		str.getBytes(Charsets.UTF_8);
	}
	System.out.println(System.currentTimeMillis() - start);
}
 
Example 3
Source Project: zabbix-sender   File: SenderRequest.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] toBytes() {
	// https://www.zabbix.org/wiki/Docs/protocols/zabbix_sender/2.0
	// https://www.zabbix.org/wiki/Docs/protocols/zabbix_sender/1.8/java_example

	byte[] jsonBytes = JSON.toJSONBytes(this);

	byte[] result = new byte[header.length + 4 + 4 + jsonBytes.length];

	System.arraycopy(header, 0, result, 0, header.length);

	result[header.length] = (byte) (jsonBytes.length & 0xFF);
	result[header.length + 1] = (byte) ((jsonBytes.length >> 8) & 0x00FF);
	result[header.length + 2] = (byte) ((jsonBytes.length >> 16) & 0x0000FF);
	result[header.length + 3] = (byte) ((jsonBytes.length >> 24) & 0x000000FF);

	System.arraycopy(jsonBytes, 0, result, header.length + 4 + 4, jsonBytes.length);
	return result;
}
 
Example 4
@Override
protected byte[] serialize() {
    try {
        byte[] json = JSON.toJSONBytes(entry, SerializerFeature.DisableCircularReferenceDetect);
        json = ZipUtil.compress(json);

        if (logger.isDebugEnabled()) {
            logger.debug("save nameservice cache, value: {}, file: {}", new String(json), file);
        }

        return json;
    } catch (Exception e) {
        logger.error("serialize cache exception", e);
        return new byte[0];
    }
}
 
Example 5
Source Project: DataLink   File: RdbEventRecordHandler.java    License: Apache License 2.0 6 votes vote down vote up
private static void submitToKafka(DBTableRowVO rowVO, String topic, KafkaWriterParameter kafkaWriterParameter, KafkaFactory.KafkaClientModel kafkaClientModel) {

        topic = KafkaUtils.getTopic(topic, rowVO.getDatabaseName(), rowVO.getTableName());
        byte[] data;
        if (kafkaWriterParameter.getSerializeMode() == SerializeMode.Hessian) {
            data = HessianUtil.serialize(rowVO);
        } else if (kafkaWriterParameter.getSerializeMode() == SerializeMode.Json) {
            data = JSON.toJSONBytes(rowVO);
        } else {
            throw new UnsupportedOperationException("Invalid SerializeMode " + kafkaWriterParameter.getSerializeMode());
        }

        //兼容老数据,为空时为id方式
        String haseKey = rowVO.getDatabaseName() + rowVO.getTableName() + rowVO.getId();
        if (kafkaWriterParameter.getPartitionMode() == PartitionMode.TABLE) {
            haseKey = rowVO.getDatabaseName() + rowVO.getTableName();
        }

        try {
            kafkaClientModel.getKafkaProducer().send(new ProducerRecord(topic, haseKey, data));
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }
 
Example 6
Source Project: DataLink   File: TaskStatusServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void addStatus(TaskStatus status) throws TaskConflictException {
    DLinkZkUtils zkUtils = DLinkZkUtils.get();
    String statusPath = DLinkZkPathDef.getTaskStatusNode(status.getId());

    byte[] bytes = JSON.toJSONBytes(status);
    try {
        zkUtils.zkClient().createPersistent(DLinkZkPathDef.getTaskNode(status.getId()), true);
        zkUtils.zkClient().create(statusPath, bytes, CreateMode.EPHEMERAL);
    } catch (ZkNodeExistsException e) {
        byte[] data = zkUtils.zkClient().readData(statusPath, true);
        if (data != null) {
            TaskStatus otherTaskStatus = JSON.parseObject(data, TaskStatus.class);
            throw new TaskConflictException(status.getId(), status.getWorkerId(), otherTaskStatus.getWorkerId(),
                    status.getExecutionId(), otherTaskStatus.getExecutionId());
        } else {
            addStatus(status);
        }
    }
}
 
Example 7
@Override
public byte[] serialize(T t) throws SerializationException {
    if (t == null) {
        return new byte[0];
    }
    try {
        return JSON.toJSONBytes(t, fastJsonConfig.getSerializeConfig(), fastJsonConfig.getSerializerFeatures());
    } catch (Exception ex) {
        throw new SerializationException("Could not serialize: " + ex.getMessage(), ex);
    }
}
 
Example 8
Source Project: phone   File: FastJsonJsonSerializer.java    License: Apache License 2.0 5 votes vote down vote up
public byte[] serialize(Object t) throws SerializationException {

		if (t == null) {
			return EMPTY_ARRAY;
		}
		try {
			return JSON.toJSONBytes(t);
		} catch (Exception ex) {
			throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);
		}
	}
 
Example 9
Source Project: DataLink   File: HRecordHandler.java    License: Apache License 2.0 5 votes vote down vote up
void submitToKafka(Map<String, Object> map, String topic, KafkaWriterParameter kafkaWriterParameter, KafkaFactory.KafkaClientModel kafkaClientModel) {
    String namespace = map.get("namespace").toString();
    String tableName = map.get("tableName").toString();

    topic = KafkaUtils.getTopic(namespace, tableName, topic);

    //兼容老数据,为空时为id方式
    String haseKey = namespace + tableName + map.get("rowkey");
    if (kafkaWriterParameter.getPartitionMode() == PartitionMode.TABLE) {
        haseKey = namespace + tableName;
    }

    byte[] data;
    if (kafkaWriterParameter.getSerializeMode() == SerializeMode.Hessian) {
        data = HessianUtil.serialize(map);
    } else if (kafkaWriterParameter.getSerializeMode() == SerializeMode.Json) {
        data = JSON.toJSONBytes(map);
    } else {
        throw new UnsupportedOperationException("Invalid SerializeMode " + kafkaWriterParameter.getSerializeMode());
    }

    try {
        kafkaClientModel.getKafkaProducer().send(new ProducerRecord(topic, haseKey, data));
    } catch (Exception e) {
        logger.error(e.getMessage());
        throw new RuntimeException(e);
    }
}
 
Example 10
Source Project: xipki   File: DemoCertprofile.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean initExtraExtension(ExtensionType extn) throws CertprofileException {
  ASN1ObjectIdentifier extnId = extn.getType().toXiOid();
  if (id_demo_without_conf.equals(extnId)) {
    this.addExtraWithoutConf = true;
    return true;
  } else if (id_demo_with_conf.equals(extnId)) {
    Object customObj = extn.getCustom();
    if (customObj == null) {
      throw new CertprofileException("ExtensionType.custom is not specified");
    }

    if (!(customObj instanceof JSONObject)) {
      throw new CertprofileException("ExtensionType.custom is not configured correctly");
    }

    // we need to first serialize the configuration
    byte[] serializedConf = JSON.toJSONBytes(customObj);
    ExtnDemoWithConf conf = JSON.parseObject(serializedConf, ExtnDemoWithConf.class);

    List<String> list = conf.getTexts();
    DERUTF8String[] texts = new DERUTF8String[list.size()];
    for (int i = 0; i < list.size(); i++) {
      texts[i] = new DERUTF8String(list.get(i));
    }

    this.sequence = new DERSequence(texts);

    this.addExtraWithConf = true;
    return true;
  } else {
    return false;
  }
}
 
Example 11
@Override
public byte[] serialize(ServiceInstance<T> instance) {
    return JSON.toJSONBytes(instance);
}
 
Example 12
Source Project: hermes   File: JsonPayloadCodec.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public byte[] doEncode(String topic, Object input) {
	return JSON.toJSONBytes(input);
}
 
Example 13
Source Project: metrics   File: DataSource.java    License: Apache License 2.0 4 votes vote down vote up
public byte[] toJsonBytes() {
	return JSON.toJSONBytes(this, SerializerFeature.QuoteFieldNames);
}
 
Example 14
Source Project: feeyo-hlsserver   File: JsonUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static byte[] marshalToByte(Object obj, SerializerFeature... features) {
    return JSON.toJSONBytes(obj, features); // 默认为UTF-8
}
 
Example 15
@Override
public byte[] serialize(T payloadBean) {
    return JSON.toJSONBytes(payloadBean);
}
 
Example 16
Source Project: elephant   File: JsonSerializer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <T> byte[] serializer(T obj) {
	JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	return JSON.toJSONBytes(obj, SerializerFeature.WriteDateUseDateFormat);
}
 
Example 17
Source Project: xipki   File: HealthCheckServlet.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
    throws ServletException, IOException {
  resp.setHeader("Access-Control-Allow-Origin", "*");

  try {
    String caName = null;
    CmpResponder responder = null;

    String path = (String) req.getAttribute(HttpConstants.ATTR_XIPKI_PATH);
    if (path.length() > 1) {
      // skip the first char which is always '/'
      String caAlias = path.substring(1);
      caName = responderManager.getCaNameForAlias(caAlias);
      if (caName == null) {
        caName = caAlias.toLowerCase();
      }
      responder = responderManager.getX509CaResponder(caName);
    }

    if (caName == null || responder == null || !responder.isOnService()) {
      String auditMessage;
      if (caName == null) {
        auditMessage = "no CA is specified";
      } else if (responder == null) {
        auditMessage = "unknown CA '" + caName + "'";
      } else {
        auditMessage = "CA '" + caName + "' is out of service";
      }
      LOG.warn(auditMessage);

      sendError(resp, HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    HealthCheckResult healthResult = responder.healthCheck();
    int status = healthResult.isHealthy()
        ? HttpServletResponse.SC_OK
        : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    byte[] respBytes = JSON.toJSONBytes(healthResult);
    resp.setStatus(status);
    resp.setContentLength(respBytes.length);
    resp.setContentType(CT_RESPONSE);
    resp.getOutputStream().write(respBytes);
  } catch (Throwable th) {
    if (th instanceof EOFException) {
      LogUtil.warn(LOG, th, "connection reset by peer");
    } else {
      LOG.error("Throwable thrown, this should not happen!", th);
    }
    sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  } finally {
    resp.flushBuffer();
  }
}
 
Example 18
Source Project: feeyo-hlsserver   File: JsonUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static byte[] marshalToByte(Object obj) {
    return JSON.toJSONBytes(obj); // 默认为UTF-8
}
 
Example 19
Source Project: buddha   File: FastJsonSerializer.java    License: MIT License 4 votes vote down vote up
public byte[] serialize(Object object) {
    byte[] bytes = JSON.toJSONBytes(object, SerializerFeature.SortField);
    return bytes;
}
 
Example 20
Source Project: xipki   File: OcspMgmtClient.java    License: Apache License 2.0 4 votes vote down vote up
private byte[] transmit(MgmtAction action, MgmtRequest req, boolean voidReturn)
    throws OcspMgmtException {
  initIfNotDone();

  byte[] reqBytes = req == null ? null : JSON.toJSONBytes(req);
  int size = reqBytes == null ? 0 : reqBytes.length;

  URL url = actionUrlMap.get(action);

  try {
    HttpURLConnection httpUrlConnection = IoUtil.openHttpConn(url);
    if (httpUrlConnection instanceof HttpsURLConnection) {
      if (sslSocketFactory != null) {
        ((HttpsURLConnection) httpUrlConnection).setSSLSocketFactory(sslSocketFactory);
      }
      if (hostnameVerifier != null) {
        ((HttpsURLConnection) httpUrlConnection).setHostnameVerifier(hostnameVerifier);
      }
    }

    httpUrlConnection.setDoOutput(true);
    httpUrlConnection.setUseCaches(false);

    httpUrlConnection.setRequestMethod("POST");
    httpUrlConnection.setRequestProperty("Content-Type", REQUEST_CT);
    httpUrlConnection.setRequestProperty("Content-Length", java.lang.Integer.toString(size));
    OutputStream outputstream = httpUrlConnection.getOutputStream();
    if (size != 0) {
      outputstream.write(reqBytes);
    }
    outputstream.flush();

    if (httpUrlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
      InputStream in = httpUrlConnection.getInputStream();

      boolean inClosed = false;
      try {
        String responseContentType = httpUrlConnection.getContentType();
        if (!RESPONSE_CT.equals(responseContentType)) {
          throw new OcspMgmtException(
              "bad response: mime type " + responseContentType + " not supported!");
        }

        if (voidReturn) {
          return null;
        } else {
          inClosed = true;
          return IoUtil.read(httpUrlConnection.getInputStream());
        }
      } finally {
        if (in != null & !inClosed) {
          in.close();
        }
      }
    } else {
      String errorMessage = httpUrlConnection.getHeaderField(HttpConstants.HEADER_XIPKI_ERROR);
      if (errorMessage == null) {
        StringBuilder sb = new StringBuilder(100);
        sb.append("server returns ").append(httpUrlConnection.getResponseCode());
        String respMsg = httpUrlConnection.getResponseMessage();
        if (StringUtil.isNotBlank(respMsg)) {
          sb.append(" ").append(respMsg);
        }
        throw new OcspMgmtException(sb.toString());
      } else {
        throw new OcspMgmtException(errorMessage);
      }
    }
  } catch (IOException ex) {
    throw new OcspMgmtException(
        "IOException while sending message to the server: " + ex.getMessage(), ex);
  }
}