Пример #1
0
NS_IMETHODIMP
nsJSON::Encode(const JS::Value& aValue, JSContext* cx, uint8_t aArgc,
               nsAString &aJSON)
{
  // This function should only be called from JS.
  nsresult rv = WarnDeprecatedMethod(EncodeWarning);
  if (NS_FAILED(rv))
    return rv;

  if (aArgc == 0) {
    aJSON.Truncate();
    aJSON.SetIsVoid(true);
    return NS_OK;
  }

  nsJSONWriter writer;
  rv = EncodeInternal(cx, aValue, &writer);

  // FIXME: bug 408838. Get exception types sorted out
  if (NS_SUCCEEDED(rv) || rv == NS_ERROR_INVALID_ARG) {
    rv = NS_OK;
    // if we didn't consume anything, it's not JSON, so return null
    if (!writer.DidWrite()) {
      aJSON.Truncate();
      aJSON.SetIsVoid(true);
    } else {
      writer.FlushBuffer();
      aJSON.Append(writer.mOutputString);
    }
  }

  return rv;
}
Пример #2
0
NS_IMETHODIMP
nsJSON::EncodeToStream(nsIOutputStream *aStream,
                       const char* aCharset,
                       const bool aWriteBOM,
                       const JS::Value& val,
                       JSContext* cx,
                       uint8_t aArgc)
{
  // This function should only be called from JS.
  NS_ENSURE_ARG(aStream);
  nsresult rv;

  rv = CheckCharset(aCharset);
  NS_ENSURE_SUCCESS(rv, rv);

  // Check to see if we have a buffered stream
  nsCOMPtr<nsIOutputStream> bufferedStream;
  // FIXME: bug 408514.
  // NS_OutputStreamIsBuffered(aStream) asserts on file streams...
  //if (!NS_OutputStreamIsBuffered(aStream)) {
    rv = NS_NewBufferedOutputStream(getter_AddRefs(bufferedStream),
                                    aStream, 4096);
    NS_ENSURE_SUCCESS(rv, rv);
  //  aStream = bufferedStream;
  //}

  uint32_t ignored;
  if (aWriteBOM) {
    if (strcmp(aCharset, "UTF-8") == 0)
      rv = aStream->Write(UTF8BOM, 3, &ignored);
    else if (strcmp(aCharset, "UTF-16LE") == 0)
      rv = aStream->Write(UTF16LEBOM, 2, &ignored);
    else if (strcmp(aCharset, "UTF-16BE") == 0)
      rv = aStream->Write(UTF16BEBOM, 2, &ignored);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  nsJSONWriter writer(bufferedStream);
  rv = writer.SetCharset(aCharset);
  NS_ENSURE_SUCCESS(rv, rv);

  if (aArgc == 0) {
    return NS_OK;
  }

  rv = EncodeInternal(cx, val, &writer);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = bufferedStream->Flush();

  return rv;
}
Пример #3
0
//
// AString encode(in JSObject value, [optional] in JSObject whitelist);
//
NS_IMETHODIMP
nsJSON::Encode(nsAString &aJSON)
{
  // This function should only be called from JS.
  nsresult rv;

  nsJSONWriter writer;
  rv = EncodeInternal(&writer);

  // FIXME: bug 408838. Get exception types sorted out
  if (NS_SUCCEEDED(rv) || rv == NS_ERROR_INVALID_ARG) {
    rv = NS_OK;
    // if we didn't consume anything, it's not JSON, so return null
    if (!writer.DidWrite()) {
      aJSON.Truncate();
      aJSON.SetIsVoid(PR_TRUE);
    } else {
      writer.FlushBuffer();
      aJSON.Append(writer.mOutputString);
    }
  }

  return rv;
}