Class CBORObject
- All Implemented Interfaces:
Comparable<CBORObject>
Represents an object in Concise Binary Object Representation (CBOR) and contains methods for reading and writing CBOR data. CBOR is an Internet Standard and defined in RFC 8949.
Converting CBOR objects
There are many ways to get a CBOR object, including from bytes, objects, streams and JSON, as described below.
To and from byte arrays: The CBORObject.DecodeFromBytes method converts a byte array in CBOR format to a CBOR object. The EncodeToBytes method converts a CBOR object to its corresponding byte array in CBOR format.
To and from data streams: The CBORObject.Write methods write many kinds of objects to a data stream, including numbers, CBOR objects, strings, and arrays of numbers and strings. The CBORObject.Read method reads a CBOR object from a data stream.
To and from other objects: The
CBORObject.FromObject method converts many kinds of objects to a CBOR
object, including numbers, strings, and arrays and maps of numbers and
strings. Methods like AsNumber and AsString convert a CBOR object to
different types of object. The CBORObject.ToObject method converts a
CBOR object to an object of a given type; for example, a CBOR array to a
native ArrayList (or ArrayList in Java), or a CBOR integer
to an int or long.
To and from JSON: This class also doubles as a reader and writer of JavaScript object Notation (JSON). The CBORObject.FromJSONString method converts JSON in text string form to a CBOR object, and the ToJSONString method converts a CBOR object to a JSON string. (Note that the conversion from CBOR to JSON is not always without loss and may make it impossible to recover the original object when converting the JSON back to CBOR. See the ToJSONString documentation.) Likewise, ToJSONBytes and FromJSONBytes work with JSON in the form of byte arrays rather than text strings.
In addition, the CBORObject.WriteJSON method writes many kinds of objects as JSON to a data stream, including numbers, CBOR objects, strings, and arrays of numbers and strings. The CBORObject.Read method reads a CBOR object from a JSON data stream.
Comparison Considerations:
Instances of CBORObject should not be compared for equality using the "==" operator; it's possible to create two CBOR objects with the same value but not the same reference. (The "==" operator might only check if each side of the operator is the same instance.)
This class's natural ordering (under the
compareTo method) is consistent with the Equals method, meaning that two
values that compare as equal under the compareTo method are also equal under
the Equals method; this is a change in version 4.0. Two otherwise equal
objects with different tags are not treated as equal by both compareTo and
Equals. To strip the tags from a CBOR object before comparing, use the
Untag method.
Thread Safety:
Certain CBOR objects are immutable (their values can't be changed), so they are inherently safe for use by multiple threads.
CBOR objects that are arrays, maps, and byte strings (whether or not they are tagged) are mutable, but this class doesn't attempt to synchronize reads and writes to those objects by multiple threads, so those objects are not thread safe without such synchronization.
One kind of CBOR object is called a map, or a list of key-value pairs. Keys can be any kind of CBOR object, including numbers, strings, arrays, and maps. However, untagged text strings (which means GetTags returns an empty array and the Type property, or "getType()" in Java, returns TextString) are the most suitable to use as keys; other kinds of CBOR object are much better used as map values instead, keeping in mind that some of them are not thread safe without synchronizing reads and writes to them.
To find the type of a CBOR object, call its Type property (or "getType()" in Java). The return value can be Integer, FloatingPoint, Boolean, SimpleValue, or TextString for immutable CBOR objects, and Array, Map, or ByteString for mutable CBOR objects.
Nesting Depth:
The DecodeFromBytes and Read methods can only read objects with a limited maximum depth of arrays and maps nested within other arrays and maps. The code sets this maximum depth to 500 (allowing more than enough nesting for most purposes), but it's possible that stack overflows in some runtimes might lower the effective maximum nesting depth. When the nesting depth goes above 500, the DecodeFromBytes and Read methods throw a CBORException.
The ReadJSON and FromJSONString methods currently have nesting depths of 1000.
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final CBORObjectRepresents the value false.static final CBORObjectA not-a-number value.static final CBORObjectThe value negative infinity.static final CBORObjectRepresents the value null.static final CBORObjectThe value positive infinity.static final CBORObjectRepresents the value true.static final CBORObjectRepresents the value undefined.static final CBORObjectGets a CBOR object for the number zero. -
Method Summary
Modifier and TypeMethodDescriptionAbs()Deprecated.Instead, convert this object to a number (with .getAsNumber()()), and use that number's.getAbs()() method.Add(CBORObject obj) Adds a new object to the end of this array.Converts an object to a CBOR object and adds it to the end of this array.Adds a new key and its value to this CBOR map, or adds the value if the key doesn't exist.static CBORObjectAddition(CBORObject first, CBORObject second) Deprecated.Instead, convert both CBOR objects to numbers (with .AsNumber()), and use the first number's.Add() method.ApplyJSONPatch(CBORObject patch) Returns a copy of this object after applying the operations in a JSON patch, in the form of a CBOR object.booleanReturns false if this object is a CBOR false, null, or undefined value (whether or not the object has tags); otherwise, true.byteAsByte()Deprecated.Instead, use.getToObject()<byte>() in .NET or .getToObject()(Byte.class) in Java.doubleAsDouble()Converts this object to a 64-bit floating point number.longConverts this object to the bits of a 64-bit floating-point number if this CBOR object's type is FloatingPoint.doubleConverts this object to a 64-bit floating-point number if this CBOR object's type is FloatingPoint.com.upokecenter.numbers.EDecimalDeprecated.Instead, use.getToObject()<PeterO.Numbers.EDecimal>() in .NET or .getToObject()(com.upokecenter.numbers.EDecimal.class) in Java.com.upokecenter.numbers.EFloatAsEFloat()Deprecated.Instead, use.getToObject()<PeterO.Numbers.EFloat>() in.NET or .getToObject()(com.upokecenter.numbers.EFloat.class) in Java.com.upokecenter.numbers.EIntegerDeprecated.Instead, use.getToObject()<PeterO.Numbers.EInteger>() in .NET or .getToObject()(com.upokecenter.numbers.EInteger.class) in Java.com.upokecenter.numbers.EIntegerConverts this object to an arbitrary-precision integer if this CBOR object's type is Integer.com.upokecenter.numbers.ERationalDeprecated.Instead, use.getToObject()<PeterO.Numbers.ERational>() in .NET or.getToObject()(com.upokecenter.numbers.ERational.class) in Java.shortAsInt16()Deprecated.Instead, use the following: (cbor.AsNumber().ToInt16Checked()), or .getToObject()<short>() in .NET.intAsInt32()Converts this object to a 32-bit signed integer.intConverts this object to a 32-bit signed integer if this CBOR object's type is Integer.longAsInt64()Deprecated.Instead, use the following: (cbor.AsNumber().ToInt64Checked()), or .ToObject<long>() in.NET.longConverts this object to a 64-bit signed integer if this CBOR object's type is Integer.AsNumber()Converts this object to a CBOR number.floatAsSingle()Converts this object to a 32-bit floating point number.AsString()Gets the value of this object as a text string.AtJSONPointer(String pointer) Gets the CBOR object referred to by a JSON Pointer according to RFC6901.AtJSONPointer(String pointer, CBORObject defaultValue) Gets the CBOR object referred to by a JSON Pointer according to RFC6901, or a default value if the operation fails.longCalculates the number of bytes this CBOR object takes when serialized as a byte array using theEncodeToBytes()method.booleanDeprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().CanFitInDouble()).booleanDeprecated.Instead, use.CanValueFitInInt32(), if the application allows only CBOR integers, or (cbor.isNumber() &&cbor.AsNumber().CanFitInInt32()), if the application allows any CBOR Object convertible to an integer.booleanDeprecated.Instead, use CanValueFitInInt64(), if the application allows only CBOR integers, or (cbor.isNumber() &&cbor.AsNumber().CanFitInInt64()), if the application allows any CBOR Object convertible to an integer.booleanDeprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().CanFitInSingle()).booleanDeprecated.Instead, use the following: (cbor.CanValueFitInInt32() if only integers of any tag are allowed, or (cbor.isNumber() && cbor.AsNumber().CanTruncatedIntFitInInt32()).booleanDeprecated.Instead, use the following: (cbor.CanValueFitInInt64() if only integers of any tag are allowed, or (cbor.isNumber() && cbor.AsNumber().CanTruncatedIntFitInInt64()).booleanReturns whether this CBOR object stores an integer (CBORType.Integer) within the range of a 32-bit signed integer.booleanReturns whether this CBOR object stores an integer (CBORType.Integer) within the range of a 64-bit signed integer.voidClear()Removes all items from this CBOR array or all keys and values from this CBOR map.intcompareTo(CBORObject other) Compares two CBOR objects.intCompareToIgnoreTags(CBORObject other) Compares this object and another CBOR object, ignoring the tags they have, if any.booleanContainsKey(CBORObject key) Determines whether a value of the given key exists in this object.booleanContainsKey(Object objKey) Determines whether a value of the given key exists in this object.booleanContainsKey(String key) Determines whether a value of the given key exists in this object.static CBORObjectDecodeFromBytes(byte[] data) Generates a CBOR object from an array of CBOR-encoded bytes.static CBORObjectDecodeFromBytes(byte[] data, CBOREncodeOptions options) Generates a CBOR object from an array of CBOR-encoded bytes, using the givenCBOREncodeOptionsobject to control the decoding process.static <T> TDecodeObjectFromBytes(byte[] data, CBOREncodeOptions enc, Type t) Generates an object of an arbitrary type from an array of CBOR-encoded bytes, using the givenCBOREncodeOptionsobject to control the decoding process.static <T> TDecodeObjectFromBytes(byte[] data, CBOREncodeOptions enc, Type t, CBORTypeMapper mapper, PODOptions pod) Generates an object of an arbitrary type from an array of CBOR-encoded bytes, using the givenCBOREncodeOptionsobject to control the decoding process.static <T> TDecodeObjectFromBytes(byte[] data, Type t) Generates an object of an arbitrary type from an array of CBOR-encoded bytes.static <T> TDecodeObjectFromBytes(byte[] data, Type t, CBORTypeMapper mapper, PODOptions pod) Generates an object of an arbitrary type from an array of CBOR-encoded bytes.static CBORObject[]DecodeSequenceFromBytes(byte[] data) Generates a sequence of CBOR objects from an array of CBOR-encoded bytes.static CBORObject[]DecodeSequenceFromBytes(byte[] data, CBOREncodeOptions options) Generates a sequence of CBOR objects from an array of CBOR-encoded bytes.static CBORObjectDivide(CBORObject first, CBORObject second) Deprecated.Instead, convert both CBOR objects to numbers (with .AsNumber()), and use the first number's.Divide() method.byte[]Writes the binary representation of this CBOR object and returns a byte array of that representation.byte[]EncodeToBytes(CBOREncodeOptions options) Writes the binary representation of this CBOR object and returns a byte array of that representation, using the specified options for encoding the object to CBOR format.booleanequals(CBORObject other) Compares the equality of two CBOR objects.booleanDetermines whether this object and another object are equal and have the same type.static CBORObjectFromFloatingPointBits(long floatingBits, int byteCount) Generates a CBOR object from a floating-point number represented by its bits.static CBORObjectFromJSONBytes(byte[] bytes) Generates a CBOR object from a byte array in JavaScript object Notation (JSON) format.static CBORObjectFromJSONBytes(byte[] bytes, int offset, int count) Generates a CBOR object from a byte array in JavaScript object Notation (JSON) format.static CBORObjectFromJSONBytes(byte[] bytes, int offset, int count, JSONOptions jsonoptions) Generates a CBOR object from a byte array in JavaScript object Notation (JSON) format, using the specified options to control the decoding process.static CBORObjectFromJSONBytes(byte[] bytes, JSONOptions jsonoptions) Generates a CBOR object from a byte array in JavaScript object Notation (JSON) format, using the specified options to control the decoding process.static CBORObject[]FromJSONSequenceBytes(byte[] bytes) Generates a list of CBOR objects from an array of bytes in JavaScript object Notation (JSON) text sequence format (RFC 7464).static CBORObject[]FromJSONSequenceBytes(byte[] data, JSONOptions options) Generates a list of CBOR objects from an array of bytes in JavaScript object Notation (JSON) text sequence format (RFC 7464), using the specified options to control the decoding process.static CBORObjectFromJSONString(String str) Generates a CBOR object from a text string in JavaScript object Notation (JSON) format.static CBORObjectFromJSONString(String str, int offset, int count) Generates a CBOR object from a text string in JavaScript object Notation (JSON) format.static CBORObjectFromJSONString(String str, int offset, int count, JSONOptions jsonoptions) Generates a CBOR object from a text string in JavaScript object Notation (JSON) format, using the specified options to control the decoding process.static CBORObjectFromJSONString(String str, CBOREncodeOptions options) Deprecated.Instead, use.getFromJSONString()(str, new JSONOptions(\allowduplicatekeys = true\)) or .getFromJSONString()(str, new JSONOptions(\allowduplicatekeys = false\)), as appropriate.static CBORObjectFromJSONString(String str, JSONOptions jsonoptions) Generates a CBOR object from a text string in JavaScript object Notation (JSON) format, using the specified options to control the decoding process.static CBORObjectFromObject(boolean value) Returns the CBOR true value or false value, depending on "value".static CBORObjectFromObject(byte value) Generates a CBOR object from a byte (0 to 255).static CBORObjectFromObject(byte[] bytes) Generates a CBOR object from an array of 8-bit bytes; the byte array is copied to a new byte array in this process.static CBORObjectFromObject(double value) Generates a CBOR object from a 64-bit floating-point number.static CBORObjectFromObject(float value) Generates a CBOR object from a 32-bit floating-point number.static CBORObjectFromObject(int value) Generates a CBOR object from a 32-bit signed integer.static CBORObjectFromObject(int[] array) Generates a CBOR object from an array of 32-bit integers.static CBORObjectFromObject(long value) Generates a CBOR object from a 64-bit signed integer.static CBORObjectFromObject(long[] array) Generates a CBOR object from an array of 64-bit integers.static CBORObjectFromObject(short value) Generates a CBOR object from a 16-bit signed integer.static CBORObjectFromObject(CBORObject value) Generates a CBOR object from a CBOR object.static CBORObjectFromObject(CBORObject[] array) Generates a CBOR object from an array of CBOR objects.static CBORObjectFromObject(com.upokecenter.numbers.EDecimal bigValue) Generates a CBOR object from a decimal number.static CBORObjectFromObject(com.upokecenter.numbers.EFloat bigValue) Generates a CBOR object from an arbitrary-precision binary floating-point number.static CBORObjectFromObject(com.upokecenter.numbers.EInteger bigintValue) Generates a CBOR object from an arbitrary-precision integer.static CBORObjectFromObject(com.upokecenter.numbers.ERational bigValue) Generates a CBOR object from an arbitrary-precision rational number.static CBORObjectFromObject(Object obj) Generates a CBORObject from an arbitrary object.static CBORObjectFromObject(Object obj, CBORTypeMapper mapper) Generates a CBORObject from an arbitrary object.static CBORObjectFromObject(Object obj, CBORTypeMapper mapper, PODOptions options) Generates a CBORObject from an arbitrary object, using the given options to control how certain objects are converted to CBOR objects.static CBORObjectFromObject(Object obj, PODOptions options) Generates a CBORObject from an arbitrary object.static CBORObjectFromObject(String strValue) Generates a CBOR object from a text string.static CBORObjectFromObjectAndTag(Object valueObValue, int smallTag) Generates a CBOR object from an arbitrary object and gives the resulting object a tag in addition to its existing tags (the new tag is made the outermost tag).static CBORObjectFromObjectAndTag(Object valueOb, com.upokecenter.numbers.EInteger bigintTag) Generates a CBOR object from an arbitrary object and gives the resulting object a tag in addition to its existing tags (the new tag is made the outermost tag).static CBORObjectFromSimpleValue(int simpleValue) Creates a CBOR object from a simple value number.get(int index) Gets the value of a CBOR object by integer index in this array or by integer key in this map.get(CBORObject key) Gets the value of a CBOR object by integer index in this array or by CBOR object key in this map.Gets the value of a CBOR object in this map, using a string as the key.com.upokecenter.numbers.EInteger[]Gets a list of all tags, from outermost to innermost.byte[]Gets the backing byte array used in this CBOR object, if this object is a byte string, without copying the data to a new byte array.final Collection<Map.Entry<CBORObject, CBORObject>> Gets a collection of the key/value pairs stored in this CBOR object, if it's a map.final Collection<CBORObject> getKeys()Gets a collection of the keys of this CBOR object.final com.upokecenter.numbers.EIntegerGets the last defined tag for this CBOR data item, or -1 if the item is untagged.final com.upokecenter.numbers.EIntegerGets the outermost tag for this CBOR data item, or -1 if the item is untagged.GetOrDefault(Object key, CBORObject defaultValue) Gets the value of a CBOR object by integer index in this array or by CBOR object key in this map, or a default value if that value is not found.final intGets the simple value ID of this CBOR object, or -1 if the object is not a simple value.final intGets the number of tags this object has.final CBORTypegetType()Gets the general data type of this CBOR object.final Collection<CBORObject> Gets a collection of the values of this CBOR object, if it's a map or an array.inthashCode()Calculates the hash code of this object.booleanHasMostInnerTag(int tagValue) Returns whether this object has an innermost tag and that tag is of the given number.booleanHasMostInnerTag(com.upokecenter.numbers.EInteger bigTagValue) Returns whether this object has an innermost tag and that tag is of the given number, expressed as an arbitrary-precision number.booleanHasMostOuterTag(int tagValue) Returns whether this object has an outermost tag and that tag is of the given number.booleanHasMostOuterTag(com.upokecenter.numbers.EInteger bigTagValue) Returns whether this object has an outermost tag and that tag is of the given number.booleanReturns whether this object has only one tag.booleanHasOneTag(int tagValue) Returns whether this object has only one tag and that tag is the given number.booleanHasOneTag(com.upokecenter.numbers.EInteger bigTagValue) Returns whether this object has only one tag and that tag is the given number, expressed as an arbitrary-precision integer.booleanHasTag(int tagValue) Returns whether this object has a tag of the given number.booleanHasTag(com.upokecenter.numbers.EInteger bigTagValue) Returns whether this object has a tag of the given number.Inserts an object at the specified position in this CBOR array.final booleanisFalse()Gets a value indicating whether this value is a CBOR false value, whether tagged or not.final booleanisFinite()Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsFinite()).booleanDeprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsInfinity()).final booleanDeprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsInteger()).booleanIsNaN()Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsNaN()).final booleanDeprecated.Instead, use (cbor.IsNumber() && cbor.AsNumber().IsNegative()).booleanDeprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsNegativeInfinity()).final booleanisNull()Gets a value indicating whether this CBOR object is a CBOR null value, whether tagged or not.final booleanisNumber()Gets a value indicating whether this CBOR object stores a number (including infinity or a not-a-number or NaN value).booleanDeprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsPositiveInfinity()).final booleanisTagged()Gets a value indicating whether this data item has at least one tag.final booleanisTrue()Gets a value indicating whether this value is a CBOR true value, whether tagged or not.final booleanGets a value indicating whether this value is a CBOR undefined value, whether tagged or not.final booleanisZero()Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsZero()).static CBORObjectMultiply(CBORObject first, CBORObject second) Deprecated.Instead, convert both CBOR objects to numbers (with .AsNumber()), and use the first number's.Multiply() method.Negate()Deprecated.Instead, convert this object to a number (with .AsNumber()), and use that number's.Negate() method.static CBORObjectNewArray()Creates a new empty CBOR array.static CBORObjectNewMap()Creates a new empty CBOR map that stores its keys in an undefined order.static CBORObjectCreates a new empty CBOR map that ensures that keys are stored in the order in which they are first inserted.static CBORObjectRead(InputStream stream) Reads an object in CBOR format from a data stream.static CBORObjectRead(InputStream stream, CBOREncodeOptions options) Reads an object in CBOR format from a data stream, using the specified options to control the decoding process.static CBORObjectReadJSON(InputStream stream) Generates a CBOR object from a data stream in JavaScript object Notation (JSON) format.static CBORObjectReadJSON(InputStream stream, CBOREncodeOptions options) Deprecated.Instead, use.getReadJSON()(stream, new JSONOptions(\allowduplicatekeys = true\)) or .getReadJSON()(stream, new JSONOptions(\allowduplicatekeys = false\)), as appropriate.static CBORObjectReadJSON(InputStream stream, JSONOptions jsonoptions) Generates a CBOR object from a data stream in JavaScript object Notation (JSON) format, using the specified options to control the decoding process.static CBORObject[]ReadJSONSequence(InputStream stream) Generates a list of CBOR objects from a data stream in JavaScript object Notation (JSON) text sequence format (RFC 7464).static CBORObject[]ReadJSONSequence(InputStream stream, JSONOptions jsonoptions) Generates a list of CBOR objects from a data stream in JavaScript object Notation (JSON) text sequence format (RFC 7464).static CBORObject[]ReadSequence(InputStream stream) Reads a sequence of objects in CBOR format from a data stream.static CBORObject[]ReadSequence(InputStream stream, CBOREncodeOptions options) Reads a sequence of objects in CBOR format from a data stream.static CBORObjectRemainder(CBORObject first, CBORObject second) Deprecated.Instead, convert both CBOR objects to numbers (with .AsNumber()), and use the first number's.Remainder() method.booleanRemove(CBORObject obj) If this object is an array, removes the first instance of the specified item from the array.booleanIf this object is an array, removes the first instance of the specified item (once converted to a CBOR object) from the array.booleanRemoveAt(int index) Removes the item at the given index of this CBOR array.voidset(int index, CBORObject value) Sets the value of a CBOR object by integer index in this array or by integer key in this map.voidset(CBORObject key, CBORObject value) Sets the value of a CBOR object by integer index in this array or by CBOR object key in this map.voidset(String key, CBORObject value) Sets the value of a CBOR object in this map, using a string as the key.Maps an object to a key in this CBOR map, or adds the value if the key doesn't exist.final intsignum()Deprecated.Instead, convert this object to a number with.AsNumber(), and use the Sign property in.NET or the signum method in Java.final intsize()Gets the number of keys in this map, or the number of items in this array, or 0 if this item is neither an array nor a map.static CBORObjectSubtract(CBORObject first, CBORObject second) Deprecated.Instead, convert both CBOR objects to numbers (with .AsNumber()), and use the first number's.Subtract() method.byte[]Converts this object to a byte array in JavaScript object Notation (JSON) format.byte[]ToJSONBytes(JSONOptions jsonoptions) Converts this object to a byte array in JavaScript object Notation (JSON) format.Converts this object to a text string in JavaScript object Notation (JSON) format.ToJSONString(JSONOptions options) Converts this object to a text string in JavaScript object Notation (JSON) format, using the specified options to control the encoding process.<T> TConverts this CBOR object to an object of an arbitrary type.<T> TToObject(Type t, CBORTypeMapper mapper) Converts this CBOR object to an object of an arbitrary type.<T> TToObject(Type t, CBORTypeMapper mapper, PODOptions options) Converts this CBOR object to an object of an arbitrary type.<T> TToObject(Type t, PODOptions options) Converts this CBOR object to an object of an arbitrary type.toString()Returns this CBOR object in a text form intended to be read by humans.Untag()Gets an object with the same value as this one but without the tags it has, if any.UntagOne()Gets an object with the same value as this one but without this object's outermost tag, if any.WithTag(int smallTag) Generates a CBOR object from an arbitrary object and gives the resulting object a tag in addition to its existing tags (the new tag is made the outermost tag).WithTag(com.upokecenter.numbers.EInteger bigintTag) Generates a CBOR object from this one, but gives the resulting object a tag in addition to its existing tags (the new tag is made the outermost tag).static voidWrite(boolean value, OutputStream stream) Writes a Boolean value in CBOR format to a data stream.static voidWrite(byte value, OutputStream stream) Writes a byte (0 to 255) in CBOR format to a data stream.static voidWrite(double value, OutputStream stream) Writes a 64-bit floating-point number in CBOR format to a data stream.static voidWrite(float value, OutputStream stream) Writes a 32-bit floating-point number in CBOR format to a data stream.static voidWrite(int value, OutputStream stream) Writes a 32-bit signed integer in CBOR format to a data stream.static voidWrite(long value, OutputStream stream) Writes a 64-bit signed integer in CBOR format to a data stream.static voidWrite(short value, OutputStream stream) Writes a 16-bit signed integer in CBOR format to a data stream.static voidWrite(CBORObject value, OutputStream stream) Writes a CBOR object to a CBOR data stream.static voidWrite(com.upokecenter.numbers.EDecimal bignum, OutputStream stream) Writes a decimal floating-point number in CBOR format to a data stream, as though it were converted to a CBOR object via CBORObject.FromObject(EDecimal) and then written out.static voidWrite(com.upokecenter.numbers.EFloat bignum, OutputStream stream) Writes a binary floating-point number in CBOR format to a data stream, as though it were converted to a CBOR object via CBORObject.FromObject(EFloat) and then written out.static voidWrite(com.upokecenter.numbers.EInteger bigint, OutputStream stream) Writes a arbitrary-precision integer in CBOR format to a data stream.static voidWrite(com.upokecenter.numbers.ERational rational, OutputStream stream) Writes a rational number in CBOR format to a data stream, as though it were converted to a CBOR object via CBORObject.FromObject(ERational) and then written out.static voidWrite(Object objValue, OutputStream stream) Writes a CBOR object to a CBOR data stream.static voidWrite(Object objValue, OutputStream output, CBOREncodeOptions options) Writes an arbitrary object to a CBOR data stream, using the specified options for controlling how the object is encoded to CBOR data format.static voidWrite(String str, OutputStream stream) Writes a text string in CBOR format to a data stream.static voidWrite(String str, OutputStream stream, CBOREncodeOptions options) Writes a text string in CBOR format to a data stream, using the given options to control the encoding process.static intWriteFloatingPointBits(OutputStream outputStream, long floatingBits, int byteCount) Writes the bits of a floating-point number in CBOR format to a data stream.static intWriteFloatingPointBits(OutputStream outputStream, long floatingBits, int byteCount, boolean shortestForm) Writes the bits of a floating-point number in CBOR format to a data stream.static intWriteFloatingPointValue(OutputStream outputStream, double doubleVal, int byteCount) Writes a 64-bit binary floating-point number in CBOR format to a data stream, either in its 64-bit form, or its rounded 32-bit or 16-bit equivalent.static intWriteFloatingPointValue(OutputStream outputStream, float singleVal, int byteCount) Writes a 32-bit binary floating-point number in CBOR format to a data stream, either in its 64- or 32-bit form, or its rounded 16-bit equivalent.static voidWriteJSON(Object obj, OutputStream outputStream) Converts an arbitrary object to a text string in JavaScript object Notation (JSON) format, as in the ToJSONString method, and writes that string to a data stream in UTF-8.voidWriteJSONTo(OutputStream outputStream) Converts this object to a text string in JavaScript object Notation (JSON) format, as in the ToJSONString method, and writes that string to a data stream in UTF-8.voidWriteJSONTo(OutputStream outputStream, JSONOptions options) Converts this object to a text string in JavaScript object Notation (JSON) format, as in the ToJSONString method, and writes that string to a data stream in UTF-8, using the given JSON options to control the encoding process.voidWriteTo(OutputStream stream) Writes this CBOR object to a data stream.voidWriteTo(OutputStream stream, CBOREncodeOptions options) Writes this CBOR object to a data stream, using the specified options for encoding the data to CBOR format.static intWriteValue(OutputStream outputStream, int majorType, int value) Writes a CBOR major type number and an integer 0 or greater associated with it to a data stream, where that integer is passed to this method as a 32-bit signed integer.static intWriteValue(OutputStream outputStream, int majorType, long value) Writes a CBOR major type number and an integer 0 or greater associated with it to a data stream, where that integer is passed to this method as a 64-bit signed integer.static intWriteValue(OutputStream outputStream, int majorType, com.upokecenter.numbers.EInteger bigintValue) Writes a CBOR major type number and an integer 0 or greater associated with it to a data stream, where that integer is passed to this method as an arbitrary-precision integer.
-
Field Details
-
False
Represents the value false. -
NaN
A not-a-number value. -
NegativeInfinity
The value negative infinity. -
Null
Represents the value null. -
PositiveInfinity
The value positive infinity. -
True
Represents the value true. -
Undefined
Represents the value undefined. -
Zero
Gets a CBOR object for the number zero.
-
-
Method Details
-
size
public final int size()Gets the number of keys in this map, or the number of items in this array, or 0 if this item is neither an array nor a map.- Returns:
- The number of keys in this map, or the number of items in this array, or 0 if this item is neither an array nor a map.
-
getMostInnerTag
public final com.upokecenter.numbers.EInteger getMostInnerTag()Gets the last defined tag for this CBOR data item, or -1 if the item is untagged.- Returns:
- The last defined tag for this CBOR data item, or -1 if the item is untagged.
-
isFalse
public final boolean isFalse()Gets a value indicating whether this value is a CBOR false value, whether tagged or not.- Returns:
trueif this value is a CBOR false value; otherwise,false.
-
isFinite
Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsFinite()).Gets a value indicating whether this CBOR object represents a finite number.- Returns:
trueif this CBOR object represents a finite number; otherwise,false.
-
isIntegral
Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsInteger()).Gets a value indicating whether this object represents an integer number, that is, a number without a fractional part. Infinity and not-a-number are not considered integers.- Returns:
trueif this object represents an integer number, that is, a number without a fractional part; otherwise,false.
-
isNull
public final boolean isNull()Gets a value indicating whether this CBOR object is a CBOR null value, whether tagged or not.- Returns:
trueif this value is a CBOR null value; otherwise,false.
-
isTagged
public final boolean isTagged()Gets a value indicating whether this data item has at least one tag.- Returns:
trueif this data item has at least one tag; otherwise,false.
-
isTrue
public final boolean isTrue()Gets a value indicating whether this value is a CBOR true value, whether tagged or not.- Returns:
trueif this value is a CBOR true value; otherwise,false.
-
isUndefined
public final boolean isUndefined()Gets a value indicating whether this value is a CBOR undefined value, whether tagged or not.- Returns:
trueif this value is a CBOR undefined value; otherwise,false.
-
isZero
Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsZero()).Gets a value indicating whether this object's value equals 0.- Returns:
trueif this object's value equals 0; otherwise,false.
-
getKeys
Gets a collection of the keys of this CBOR object. In general, the order in which those keys occur is undefined unless this is a map created using the NewOrderedMap method.- Returns:
- A collection of the keys of this CBOR object. To avoid potential problems, the calling code should not modify the CBOR map or the returned collection while iterating over the returned collection.
- Throws:
IllegalStateException- This object is not a map.
-
isNegative
Deprecated.Instead, use (cbor.IsNumber() && cbor.AsNumber().IsNegative()).Gets a value indicating whether this object is a negative number.- Returns:
trueif this object is a negative number; otherwise,false.
-
getMostOuterTag
public final com.upokecenter.numbers.EInteger getMostOuterTag()Gets the outermost tag for this CBOR data item, or -1 if the item is untagged.- Returns:
- The outermost tag for this CBOR data item, or -1 if the item is untagged.
-
signum
Deprecated.Instead, convert this object to a number with.AsNumber(), and use the Sign property in.NET or the signum method in Java. Either will treat not-a-number (NaN) values differently than here.Gets this value's sign: -1 if negative; 1 if positive; 0 if zero. Throws an exception if this is a not-a-number value.- Returns:
- This value's sign: -1 if negative; 1 if positive; 0 if zero.
- Throws:
IllegalStateException- This object does not represent a number, or this object is a not-a-number (NaN) value.
-
getSimpleValue
public final int getSimpleValue()Gets the simple value ID of this CBOR object, or -1 if the object is not a simple value. In this method, objects with a CBOR type of Boolean or SimpleValue are simple values, whether they are tagged or not.- Returns:
- The simple value ID of this object if it's a simple value, or -1 if this object is not a simple value.
-
isNumber
public final boolean isNumber()Gets a value indicating whether this CBOR object stores a number (including infinity or a not-a-number or NaN value). Currently, this is true if this item is untagged and has a CBORType of Integer or FloatingPoint, or if this item has only one tag and that tag is 2, 3, 4, 5, 30, 264, 265, 268, 269, or 270 with the right data type.- Returns:
- A value indicating whether this CBOR object stores a number.
-
getType
Gets the general data type of this CBOR object. This method disregards the tags this object has, if any.- Returns:
- The general data type of this CBOR object.
-
getEntries
Gets a collection of the key/value pairs stored in this CBOR object, if it's a map. Returns one entry for each key/value pair in the map. In general, the order in which those entries occur is undefined unless this is a map created using the NewOrderedMap method.- Returns:
- A collection of the key/value pairs stored in this CBOR map, as a read-only view of those pairs. To avoid potential problems, the calling code should not modify the CBOR map while iterating over the returned collection.
- Throws:
IllegalStateException- This object is not a map.
-
getValues
Gets a collection of the values of this CBOR object, if it's a map or an array. If this object is a map, returns one value for each key in the map; in general, the order in which those keys occur is undefined unless this is a map created using the NewOrderedMap method. If this is an array, returns all the values of the array in the order they are listed. (This method can't be used to get the bytes in a CBOR byte string; for that, use the GetByteString method instead.).- Returns:
- A collection of the values of this CBOR map or array. To avoid potential problems, the calling code should not modify the CBOR map or array or the returned collection while iterating over the returned collection.
- Throws:
IllegalStateException- This object is not a map or an array.
-
get
Gets the value of a CBOR object by integer index in this array or by integer key in this map.- Parameters:
index- Index starting at 0 of the element, or the integer key to this map. (If this is a map, the given index can be any 32-bit signed integer, even a negative one.).- Returns:
- The CBOR object referred to by index or key in this array or map. If
this is a CBOR map, returns
null(notCBORObject.Null) if an item with the given key doesn't exist (but this behavior may change to throwing an exception in version 5.0 or later). - Throws:
IllegalStateException- This object is not an array or map.IllegalArgumentException- This object is an array and the index is less than 0 or at least the size of the array.NullPointerException- The parameter "value" is null (as opposed to CBORObject.Null).
-
set
Sets the value of a CBOR object by integer index in this array or by integer key in this map.- Parameters:
index- Index starting at 0 of the element, or the integer key to this map. (If this is a map, the given index can be any 32-bit signed integer, even a negative one.).- Throws:
IllegalStateException- This object is not an array or map.IllegalArgumentException- This object is an array and the index is less than 0 or at least the size of the array.NullPointerException- The parameter "value" is null (as opposed to CBORObject.Null).
-
GetOrDefault
Gets the value of a CBOR object by integer index in this array or by CBOR object key in this map, or a default value if that value is not found.- Parameters:
key- An arbitrary object. If this is a CBOR map, this parameter is converted to a CBOR object serving as the key to the map or index to the array, and can be null. If this is a CBOR array, the key must be an integer 0 or greater and less than the size of the array, and may be any object convertible to a CBOR integer.defaultValue- A value to return if an item with the given key doesn't exist, or if the CBOR object is an array and the key is not an integer 0 or greater and less than the size of the array.- Returns:
- The CBOR object referred to by index or key in this array or map. If
this is a CBOR map, returns
null(notCBORObject.Null) if an item with the given key doesn't exist.
-
get
Gets the value of a CBOR object by integer index in this array or by CBOR object key in this map.- Parameters:
key- A CBOR object serving as the key to the map or index to the array. If this is a CBOR array, the key must be an integer 0 or greater and less than the size of the array.- Returns:
- The CBOR object referred to by index or key in this array or map. If
this is a CBOR map, returns
null(notCBORObject.Null) if an item with the given key doesn't exist. - Throws:
NullPointerException- The key is null (as opposed to CBORObject.Null); or the set method is called and the value is null.IllegalArgumentException- This CBOR object is an array and the key is not an integer 0 or greater and less than the size of the array.IllegalStateException- This object is not a map or an array.
-
set
Sets the value of a CBOR object by integer index in this array or by CBOR object key in this map.- Parameters:
key- A CBOR object serving as the key to the map or index to the array. If this is a CBOR array, the key must be an integer 0 or greater and less than the size of the array.- Throws:
NullPointerException- The key is null (as opposed to CBORObject.Null); or the set method is called and the value is null.IllegalArgumentException- This CBOR object is an array and the key is not an integer 0 or greater and less than the size of the array.IllegalStateException- This object is not a map or an array.
-
get
Gets the value of a CBOR object in this map, using a string as the key.- Parameters:
key- A key that points to the desired value.- Returns:
- The CBOR object referred to by key in this map. Returns
nullif an item with the given key doesn't exist. - Throws:
NullPointerException- The key is null.IllegalStateException- This object is not a map.
-
set
Sets the value of a CBOR object in this map, using a string as the key.- Parameters:
key- A key that points to the desired value.- Throws:
NullPointerException- The key is null.IllegalStateException- This object is not a map.
-
Addition
Deprecated.Instead, convert both CBOR objects to numbers (with .AsNumber()), and use the first number's.Add() method.Finds the sum of two CBOR numbers.- Parameters:
first- The parameterfirstis a CBOR object.second- The parametersecondis a CBOR object.- Returns:
- A CBOR object.
- Throws:
IllegalArgumentException- Either or both operands are not numbers (as opposed to Not-a-Number, NaN).NullPointerException- The parameterfirstorsecondis null.
-
DecodeFromBytes
Generates a CBOR object from an array of CBOR-encoded bytes.- Parameters:
data- A byte array in which a single CBOR object is encoded.- Returns:
- A CBOR object decoded from the given byte array.
- Throws:
CBORException- There was an error in reading or parsing the data. This includes cases where not all of the byte array represents a CBOR object. This exception is also thrown if the parameterdatais empty.NullPointerException- The parameterdatais null.
-
DecodeSequenceFromBytes
Generates a sequence of CBOR objects from an array of CBOR-encoded bytes.- Parameters:
data- A byte array in which any number of CBOR objects (including zero) are encoded, one after the other. Can be empty, but cannot be null.- Returns:
- An array of CBOR objects decoded from the given byte array. Returns
an empty array if
datais empty. - Throws:
CBORException- There was an error in reading or parsing the data. This includes cases where the last CBOR object in the data was read only partly.NullPointerException- The parameterdatais null.
-
DecodeSequenceFromBytes
Generates a sequence of CBOR objects from an array of CBOR-encoded bytes.- Parameters:
data- A byte array in which any number of CBOR objects (including zero) are encoded, one after the other. Can be empty, but cannot be null.options- Specifies options to control how the CBOR object is decoded. SeeCBOREncodeOptionsfor more information. In this method, the AllowEmpty property is treated as always set regardless of that value as specified in this parameter.- Returns:
- An array of CBOR objects decoded from the given byte array. Returns
an empty array if
datais empty. - Throws:
CBORException- There was an error in reading or parsing the data. This includes cases where the last CBOR object in the data was read only partly.NullPointerException- The parameterdatais null, or the parameteroptionsis null.
-
FromJSONSequenceBytes
Generates a list of CBOR objects from an array of bytes in JavaScript object Notation (JSON) text sequence format (RFC 7464). The byte array must be in UTF-8 encoding and may not begin with a byte-order mark (U+FEFF).
Generally, each JSON text in a JSON text sequence is written as follows: Write a record separator byte (0x1e), then write the JSON text in UTF-8 (without a byte order mark, U+FEFF), then write the line feed byte (0x0a). RFC 7464, however, uses a more liberal syntax for parsing JSON text sequences.
- Parameters:
bytes- A byte array in which a JSON text sequence is encoded.- Returns:
- A list of CBOR objects read from the JSON sequence. Objects that
could not be parsed are replaced with
null(as opposed toCBORObject.Null) in the given list. - Throws:
NullPointerException- The parameterbytesis null.CBORException- The byte array is not empty and does not begin with a record separator byte (0x1e), or an I/O error occurred.
-
ToJSONBytes
public byte[] ToJSONBytes()Converts this object to a byte array in JavaScript object Notation (JSON) format. The JSON text will be written out in UTF-8 encoding, without a byte order mark, to the byte array. See the overload to ToJSONString taking a JSONOptions argument for further information.- Returns:
- A byte array containing the converted in JSON format.
-
ToJSONBytes
Converts this object to a byte array in JavaScript object Notation (JSON) format. The JSON text will be written out in UTF-8 encoding, without a byte order mark, to the byte array. See the overload to ToJSONString taking a JSONOptions argument for further information.- Parameters:
jsonoptions- Specifies options to control writing the CBOR object to JSON.- Returns:
- A byte array containing the converted object in JSON format.
- Throws:
NullPointerException- The parameterjsonoptionsis null.
-
FromJSONSequenceBytes
Generates a list of CBOR objects from an array of bytes in JavaScript object Notation (JSON) text sequence format (RFC 7464), using the specified options to control the decoding process. The byte array must be in UTF-8 encoding and may not begin with a byte-order mark (U+FEFF).
Generally, each JSON text in a JSON text sequence is written as follows: Write a record separator byte (0x1e), then write the JSON text in UTF-8 (without a byte order mark, U+FEFF), then write the line feed byte (0x0a). RFC 7464, however, uses a more liberal syntax for parsing JSON text sequences.
- Parameters:
data- A byte array in which a JSON text sequence is encoded.options- Specifies options to control the JSON decoding process.- Returns:
- A list of CBOR objects read from the JSON sequence. Objects that
could not be parsed are replaced with
null(as opposed toCBORObject.Null) in the given list. - Throws:
NullPointerException- The parameterdatais null.CBORException- The byte array is not empty and does not begin with a record separator byte (0x1e), or an I/O error occurred.
-
DecodeFromBytes
Generates a CBOR object from an array of CBOR-encoded bytes, using the given
CBOREncodeOptionsobject to control the decoding process.The following example (originally written in C# for the.NET version) implements a method that decodes a text string from a CBOR byte array. It's successful only if the CBOR object contains an untagged text string.
private static string DecodeTextString(byte[] bytes) { if (bytes == null) { throw new NullPointerException("mapObj");} if (bytes.length == 0 || bytes[0]<0x60 || bytes[0]>0x7f) {throw new CBORException();} return CBORObject.DecodeFromBytes(bytes, CBOREncodeOptions.Default).AsString(); }.- Parameters:
data- A byte array in which a single CBOR object is encoded.options- Specifies options to control how the CBOR object is decoded. SeeCBOREncodeOptionsfor more information.- Returns:
- A CBOR object decoded from the given byte array. Returns null (as
opposed to CBORObject.Null) if
datais empty and the AllowEmpty property is set on the given options object. - Throws:
CBORException- There was an error in reading or parsing the data. This includes cases where not all of the byte array represents a CBOR object. This exception is also thrown if the parameterdatais empty unless the AllowEmpty property is set on the given options object.NullPointerException- The parameterdatais null, or the parameteroptionsis null.
-
Divide
Deprecated.Instead, convert both CBOR objects to numbers (with .AsNumber()), and use the first number's.Divide() method.Divides a CBORObject object by the value of a CBORObject object.- Parameters:
first- The parameterfirstis a CBOR object.second- The parametersecondis a CBOR object.- Returns:
- The quotient of the two objects.
- Throws:
NullPointerException- The parameterfirstorsecondis null.
-
FromJSONString
Generates a CBOR object from a text string in JavaScript object Notation (JSON) format.
If a JSON object has duplicate keys, a CBORException is thrown. This is a change in version 4.0.
Note that if a CBOR object is converted to JSON with
ToJSONString, then the JSON is converted back to CBOR with this method, the new CBOR object will not necessarily be the same as the old CBOR object, especially if the old CBOR object uses data types not supported in JSON, such as integers in map keys.- Parameters:
str- A text string in JSON format. The entire string must contain a single JSON object and not multiple objects. The string may not begin with a byte-order mark (U+FEFF).offset- An index, starting at 0, showing where the desired portion ofstrbegins.count- The length, in code units, of the desired portion ofstr(but not more thanstr's length).- Returns:
- A CBOR object.
- Throws:
NullPointerException- The parameterstris null.CBORException- The string is not in JSON format.IllegalArgumentException- Eitheroffsetorcountis less than 0 or greater thanstr's length, orstr's length minusoffsetis less thancount.
-
FromJSONString
Generates a CBOR object from a text string in JavaScript object Notation (JSON) format, using the specified options to control the decoding process.
Note that if a CBOR object is converted to JSON with
ToJSONString, then the JSON is converted back to CBOR with this method, the new CBOR object will not necessarily be the same as the old CBOR object, especially if the old CBOR object uses data types not supported in JSON, such as integers in map keys.- Parameters:
str- A text string in JSON format. The entire string must contain a single JSON object and not multiple objects. The string may not begin with a byte-order mark (U+FEFF).jsonoptions- Specifies options to control the JSON decoding process.- Returns:
- A CBOR object containing the JSON data decoded.
- Throws:
NullPointerException- The parameterstrorjsonoptionsis null.CBORException- The string is not in JSON format.
-
FromJSONString
Generates a CBOR object from a text string in JavaScript object Notation (JSON) format.
If a JSON object has duplicate keys, a CBORException is thrown. This is a change in version 4.0.
Note that if a CBOR object is converted to JSON with
ToJSONString, then the JSON is converted back to CBOR with this method, the new CBOR object will not necessarily be the same as the old CBOR object, especially if the old CBOR object uses data types not supported in JSON, such as integers in map keys.- Parameters:
str- A text string in JSON format. The entire string must contain a single JSON object and not multiple objects. The string may not begin with a byte-order mark (U+FEFF).- Returns:
- A CBOR object.
- Throws:
NullPointerException- The parameterstris null.CBORException- The string is not in JSON format.
-
FromJSONString
Deprecated.Instead, use.getFromJSONString()(str, new JSONOptions(\allowduplicatekeys = true\)) or .getFromJSONString()(str, new JSONOptions(\allowduplicatekeys = false\)), as appropriate.Generates a CBOR object from a text string in JavaScript object Notation (JSON) format, using the specified options to control the decoding process.
Note that if a CBOR object is converted to JSON with
ToJSONString, then the JSON is converted back to CBOR with this method, the new CBOR object will not necessarily be the same as the old CBOR object, especially if the old CBOR object uses data types not supported in JSON, such as integers in map keys.- Parameters:
str- A text string in JSON format. The entire string must contain a single JSON object and not multiple objects. The string may not begin with a byte-order mark (U+FEFF).options- Specifies options to control the decoding process. This method uses only the AllowDuplicateKeys property of this object.- Returns:
- A CBOR object containing the JSON data decoded.
- Throws:
NullPointerException- The parameterstroroptionsis null.CBORException- The string is not in JSON format.
-
FromJSONString
Generates a CBOR object from a text string in JavaScript object Notation (JSON) format, using the specified options to control the decoding process.
Note that if a CBOR object is converted to JSON with
ToJSONString, then the JSON is converted back to CBOR with this method, the new CBOR object will not necessarily be the same as the old CBOR object, especially if the old CBOR object uses data types not supported in JSON, such as integers in map keys.- Parameters:
str- The parameterstris a text string.offset- An index, starting at 0, showing where the desired portion ofstrbegins.count- The length, in code units, of the desired portion ofstr(but not more thanstr's length).jsonoptions- The parameterjsonoptionsis a Cbor.JSONOptions object.- Returns:
- A CBOR object containing the JSON data decoded.
- Throws:
NullPointerException- The parameterstrorjsonoptionsis null.CBORException- The string is not in JSON format.IllegalArgumentException- Eitheroffsetorcountis less than 0 or greater thanstr's length, orstr's length minusoffsetis less thancount.
-
ToObject
Converts this CBOR object to an object of an arbitrary type. See the documentation for the overload of this method taking a CBORTypeMapper parameter for more information. This method doesn't use a CBORTypeMapper parameter to restrict which data types are eligible for Plain-Old-Data serialization.
Java offers no easy way to express a generic type, at least none as easy as C#'s
typeofoperator. The following example, written in Java, is a way to specify that the return value will be an ArrayList of string objects.Type arrayListString = new ParameterizedType() { public Type[] getActualTypeArguments() { /* Contains one type parameter, string*/ return new Type[] { string.class }; } public Type getRawType() { /* Raw type is ArrayList */ return ArrayList.class; } public Type getOwnerType() { return null; } }; ArrayList<string> array = (ArrayList<string>) cborArray.ToObject(arrayListString);By comparison, the C# version is much shorter.
List<string> array = (List<string>)cborArray.ToObject( typeof(List<string>));
.- Parameters:
t-The type, class, or interface that this method's return value will belong to. To express a generic type in Java, see the example. Note: For security reasons, an application should not base this parameter on user input or other externally supplied data. Whenever possible, this parameter should be either a type specially handled by this method (such as
intorstring) or a plain-old-data type (POCO or POJO type) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.- Returns:
- The converted object.
- Throws:
CBORException- The given typet, or this object's CBOR type, is not supported, or the given object's nesting is too deep, or another error occurred when serializing the object.NullPointerException- The parametertis null.
-
ToObject
Converts this CBOR object to an object of an arbitrary type. See the documentation for the overload of this method taking a CBORTypeMapper and PODOptions parameters parameters for more information.- Parameters:
t-The type, class, or interface that this method's return value will belong to. To express a generic type in Java, see the example. Note: For security reasons, an application should not base this parameter on user input or other externally supplied data. Whenever possible, this parameter should be either a type specially handled by this method (such as
intorstring) or a plain-old-data type (POCO or POJO type) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.mapper- This parameter controls which data types are eligible for Plain-Old-Data deserialization and includes custom converters from CBOR objects to certain data types.- Returns:
- The converted object.
- Throws:
CBORException- The given typet, or this object's CBOR type, is not supported, or the given object's nesting is too deep, or another error occurred when serializing the object.NullPointerException- The parametertis null.
-
ToObject
Converts this CBOR object to an object of an arbitrary type. See the documentation for the overload of this method taking a CBORTypeMapper and PODOptions parameters for more information. This method (without a CBORTypeMapper parameter) allows all data types not otherwise handled to be eligible for Plain-Old-Data serialization.- Parameters:
t-The type, class, or interface that this method's return value will belong to. To express a generic type in Java, see the example. Note: For security reasons, an application should not base this parameter on user input or other externally supplied data. Whenever possible, this parameter should be either a type specially handled by this method (such as
intorstring) or a plain-old-data type (POCO or POJO type) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.options- Specifies options for controlling deserialization of CBOR objects.- Returns:
- The converted object.
- Throws:
UnsupportedOperationException- The given typet, or this object's CBOR type, is not supported.NullPointerException- The parametertis null.CBORException- The given object's nesting is too deep, or another error occurred when serializing the object.
-
ToObject
Converts this CBOR object to an object of an arbitrary type. The following cases are checked in the logical order given (rather than the strict order in which they are implemented by this library):
- If
the type is
CBORObject, return this object. - If the given
object is
CBORObject.Null(with or without tags), returnsnull. - If the object is of a type corresponding to a type converter
mentioned in the
mapperparameter, that converter will be used to convert the CBOR object to an object of the given type. Type converters can be used to override the default conversion behavior of almost any object. - If the type is
object, return this object. - If the type is
char, converts single-character CBOR text strings and CBOR integers from 0 through 65535 to acharobject and returns thatcharobject. - If the type is
boolean(booleanin Java), returns the result of AsBoolean. - If the
type is
short, returns this number as a 16-bit signed integer after converting its value to an integer by discarding its fractional part, and throws an exception if this object's value is infinity or a not-a-number value, or does not represent a number (currently IllegalStateException, but may change in the next major version), or if the value, once converted to an integer by discarding its fractional part, is less than -32768 or greater than 32767 (currently ArithmeticException, but may change in the next major version). - If the type is
long, returns this number as a 64-bit signed integer after converting its value to an integer by discarding its fractional part, and throws an exception if this object's value is infinity or a not-a-number value, or does not represent a number (currently IllegalStateException, but may change in the next major version), or if the value, once converted to an integer by discarding its fractional part, is less than -2^63 or greater than 2^63-1 (currently ArithmeticException, but may change in the next major version). - If the type is
short, the same rules as forlongare used, but the range is from -32768 through 32767 and the return type isshort. - If the type is
byte, the same rules as forlongare used, but the range is from 0 through 255 and the return type isbyte. - If the type
is
sbyte, the same rules as forlongare used, but the range is from -128 through 127 and the return type issbyte. - If the type is
ushort, the same rules as forlongare used, but the range is from 0 through 65535 and the return type isushort. - If the type is
uint, the same rules as forlongare used, but the range is from 0 through 2^31-1 and the return type isuint. - If the type is
ulong, the same rules as forlongare used, but the range is from 0 through 2^63-1 and the return type isulong. - If the type is
intor a primitive floating-point type (float,double, as well asdecimalin.NET), returns the result of the corresponding As* method. - If the type is
string, returns the result of AsString. - If the type is
EFloat,EDecimal,EInteger, orERationalin thePeterO.Numberslibrary (in .NET) or thecom.github.peteroupc/numbersartifact (in Java), or if the type isBigIntegerorBigDecimalin the Java version, converts the given object to a number of the corresponding type and throws an exception (currently IllegalStateException) if the object does not represent a number (for this purpose, infinity and not-a-number values, but notCBORObject.Null, are considered numbers). Currently, this is equivalent to the result ofAsEFloat(),AsEDecimal(),AsEInteger, orAsERational(), respectively, but may change slightly in the next major version. Note that in the case ofEFloat, if this object represents a decimal number with a fractional part, the conversion may lose information depending on the number, and if the object is a rational number with a nonterminating binary expansion, the number returned is a binary floating-point number rounded to a high but limited precision. In the case ofEDecimal, if this object expresses a rational number with a nonterminating decimal expansion, returns a decimal number rounded to 34 digits of precision. In the case ofEInteger, if this CBOR object expresses a floating-point number, it is converted to an integer by discarding its fractional part, and if this CBOR object expresses a rational number, it is converted to an integer by dividing the numerator by the denominator and discarding the fractional part of the result, and this method throws an exception (currently ArithmeticException, but may change in the next major version) if this object expresses infinity or a not-a-number value. - In the.NET version, if the type is a nullable (e.g.,
Nullable<int>orint?, returnsnullif this CBOR object is null, or this object's value converted to the nullable's underlying type, e.g.,int. - If the type is an enumeration(
Enum) type and this CBOR object is a text string or an integer, returns the appropriate enumerated constant. (For example, ifMyEnumincludes an entry forMyValue, this method will returnMyEnum.MyValueif the CBOR object represents"MyValue"or the underlying value forMyEnum.MyValue.) Note: If an integer is converted to a.NET Enum constant, and that integer is shared by more than one constant of the same type, it is undefined which constant from among them is returned. (For example, ifMyEnum.Zero = 0andMyEnum.Null = 0, converting 0 toMyEnummay return eitherMyEnum.ZeroorMyEnum.Null.) As a result, .NET Enum types with constants that share an underlying value should not be passed to this method. - If the type is
byte[](a one-dimensional byte array) and this CBOR object is a byte string, returns a byte array which this CBOR byte string's data will be copied to. (This method can't be used to encode CBOR data to a byte array; for that, use the EncodeToBytes method instead.) - If the type is a one-dimensional or multidimensional array type and this CBOR object is an array, returns an array containing the items in this CBOR object.
- If the type is List, ReadOnlyCollection or the generic or non-generic List, ICollection, Iterable, IReadOnlyCollection, or IReadOnlyList (or ArrayList, List, Collection, or Iterable in Java), and if this CBOR object is an array, returns an object conforming to the type, class, or interface passed to this method, where the object will contain all items in this CBOR array.
- If the type is Dictionary, ReadOnlyDictionary or the generic or non-generic Map or IReadOnlyDictionary (or HashMap or Map in Java), and if this CBOR object is a map, returns an object conforming to the type, class, or interface passed to this method, where the object will contain all keys and values in this CBOR map.
- If the type is an enumeration constant ("enum"), and this CBOR object is an integer or text string, returns the enumeration constant with the given number or name, respectively. (Enumeration constants made up of multiple enumeration constants, as allowed by .NET, can only be matched by number this way.)
- If the type is
java.util.Date(orDatein Java) , returns a date/time object if the CBOR object's outermost tag == 0 || tag == 1. For tag 1, this method treats the CBOR object as a number of seconds since the start of 1970, which is based on the POSIX definition of "seconds since the Epoch", a definition that does not count leap seconds. In this method, this number of seconds assumes the use of a proleptic Gregorian calendar, in which the rules regarding the number of days in each month and which years are leap years are the same for all years as they were in 1970 (including without regard to time zone differences or transitions from other calendars to the Gregorian). The string format used in tag 0 supports only years up to 4 decimal digits long. For tag 1, CBOR objects that express infinity or not-a-number (NaN) are treated as invalid by this method. This default behavior forjava.util.DateandDatecan be changed by passing a suitable CBORTypeMapper to this method, such as a CBORTypeMapper that registers a CBORDateConverter forjava.util.DateorDateobjects. See the examples. - If the type is
java.net.URI(orURIin Java), returns a URI object if possible. - If the type is
java.util.UUID(orUUIDin Java), returns a UUID object if possible. - Plain-Old-Data deserialization: If the object is a type not specially handled above, the type includes a zero-parameter constructor (default or not), this CBOR object is a CBOR map, and the "mapper" parameter (if any) allows this type to be eligible for Plain-Old-Data deserialization, then this method checks the given type for eligible setters as follows:
- (*) In the .NET version, eligible setters are the public,
nonstatic setters of properties with a public, nonstatic getter. Eligible
setters also include public, nonstatic, non-
static final, non-readonlyfields. If a class has two properties and/or fields of the form "X" and "IsX", where "X" is any name, or has multiple properties and/or fields with the same name, those properties and fields are ignored. - (*) In the Java version, eligible setters are public, nonstatic methods starting with "set" followed by a character other than a basic digit or lower-case letter, that is, other than "a" to "z" or "0" to "9", that take one parameter. The class containing an eligible setter must have a public, nonstatic method with the same name, but starting with "get" or "is" rather than "set", that takes no parameters and does not return void. (For example, if a class has "public setValue(string)" and "public getValue()", "setValue" is an eligible setter. However, "setValue()" and "setValue(string, int)" are not eligible setters.) In addition, public, nonstatic, nonfinal fields are also eligible setters. If a class has two or more otherwise eligible setters (methods and/or fields) with the same name, but different parameter type, they are not eligible setters.
- Then,
the method creates an object of the given type and invokes each eligible
setter with the corresponding value in the CBOR map, if any. Key names in
the map are matched to eligible setters according to the rules described in
the
PODOptionsdocumentation. Note that for security reasons, certain types are not supported even if they contain eligible setters. For the Java version, the object creation may fail in the case of a nested nonstatic class.
The following example (originally written in C# for the DotNet version) uses a CBORTypeMapper to change how CBOR objects are converted to java.util.Date objects. In this case, the ToObject method assumes the CBOR object is an untagged number giving the number of seconds since the start of 1970.
CBORTypeMapper conv = new CBORTypeMapper().AddConverter(java.util.Date.class, CBORDateConverter.UntaggedNumber); CBORObject obj = CBORObject.FromObject().getToObject()<java.util.Date>(conv);
Java offers no easy way to express a generic type, at least none as easy as C#'s
typeofoperator. The following example, written in Java, is a way to specify that the return value will be an ArrayList of string objects.Type arrayListString = new ParameterizedType() { public Type[] getActualTypeArguments() { /* Contains one type parameter, string*/ return new Type[] { string.class }; } public Type getRawType() { /* Raw type is ArrayList */ return ArrayList.class; } public Type getOwnerType() { return null; } }; ArrayList<string> array = (ArrayList<string>) cborArray.ToObject(arrayListString);By comparison, the C# version is much shorter.
List<string> array = (List<string>)cborArray.ToObject(typeof(List<string>));
.- Parameters:
t-The type, class, or interface that this method's return value will belong to. To express a generic type in Java, see the example. Note: For security reasons, an application should not base this parameter on user input or other externally supplied data. Whenever possible, this parameter should be either a type specially handled by this method, such as
intorstring, or a plain-old-data type (POCO or POJO type) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.mapper- This parameter controls which data types are eligible for Plain-Old-Data deserialization and includes custom converters from CBOR objects to certain data types. Can be null.options- Specifies options for controlling deserialization of CBOR objects.- Returns:
- The converted object.
- Throws:
CBORException- The given typet, or this object's CBOR type, is not supported, or the given object's nesting is too deep, or another error occurred when serializing the object.NullPointerException- The parametertoroptionsis null.
- If
the type is
-
DecodeObjectFromBytes
public static <T> T DecodeObjectFromBytes(byte[] data, CBOREncodeOptions enc, Type t, CBORTypeMapper mapper, PODOptions pod) Generates an object of an arbitrary type from an array of CBOR-encoded bytes, using the givenCBOREncodeOptionsobject to control the decoding process. It is equivalent to DecodeFromBytes followed by ToObject. See the documentation for those methods for more information.- Parameters:
data- A byte array in which a single CBOR object is encoded.enc- Specifies options to control how the CBOR object is decoded. SeeCBOREncodeOptionsfor more information.t-The type, class, or interface that this method's return value will belong to. To express a generic type in Java, see the example. Note: For security reasons, an application should not base this parameter on user input or other externally supplied data. Whenever possible, this parameter should be either a type specially handled by this method, such as
intorstring, or a plain-old-data type (POCO or POJO type) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.mapper- This parameter controls which data types are eligible for Plain-Old-Data deserialization and includes custom converters from CBOR objects to certain data types. Can be null.pod- Specifies options for controlling deserialization of CBOR objects.- Returns:
- An object of the given type decoded from the given byte array.
Returns null (as opposed to CBORObject.Null) if
datais empty and the AllowEmpty property is set on the given CBOREncodeOptions object. - Throws:
CBORException- There was an error in reading or parsing the data. This includes cases where not all of the byte array represents a CBOR object. This exception is also thrown if the parameterdatais empty unless the AllowEmpty property is set on the given options object. Also thrown if the given typet, or this object's CBOR type, is not supported, or the given object's nesting is too deep, or another error occurred when serializing the object.NullPointerException- The parameterdatais null, or the parameterencis null, or the parametertorpodis null.
-
DecodeObjectFromBytes
Generates an object of an arbitrary type from an array of CBOR-encoded bytes, using the givenCBOREncodeOptionsobject to control the decoding process. It is equivalent to DecodeFromBytes followed by ToObject. See the documentation for those methods for more information.- Parameters:
data- A byte array in which a single CBOR object is encoded.enc- Specifies options to control how the CBOR object is decoded. SeeCBOREncodeOptionsfor more information.t-The type, class, or interface that this method's return value will belong to. To express a generic type in Java, see the example. Note: For security reasons, an application should not base this parameter on user input or other externally supplied data. Whenever possible, this parameter should be either a type specially handled by this method, such as
intorstring, or a plain-old-data type (POCO or POJO type) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.- Returns:
- An object of the given type decoded from the given byte array.
Returns null (as opposed to CBORObject.Null) if
datais empty and the AllowEmpty property is set on the given CBOREncodeOptions object. - Throws:
CBORException- There was an error in reading or parsing the data. This includes cases where not all of the byte array represents a CBOR object. This exception is also thrown if the parameterdatais empty unless the AllowEmpty property is set on the given options object. Also thrown if the given typet, or this object's CBOR type, is not supported, or the given object's nesting is too deep, or another error occurred when serializing the object.NullPointerException- The parameterdatais null, or the parameterencis null, or the parametertis null.
-
DecodeObjectFromBytes
public static <T> T DecodeObjectFromBytes(byte[] data, Type t, CBORTypeMapper mapper, PODOptions pod) Generates an object of an arbitrary type from an array of CBOR-encoded bytes. It is equivalent to DecodeFromBytes followed by ToObject. See the documentation for those methods for more information.- Parameters:
data- A byte array in which a single CBOR object is encoded.t-The type, class, or interface that this method's return value will belong to. To express a generic type in Java, see the example. Note: For security reasons, an application should not base this parameter on user input or other externally supplied data. Whenever possible, this parameter should be either a type specially handled by this method, such as
intorstring, or a plain-old-data type (POCO or POJO type) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.mapper- This parameter controls which data types are eligible for Plain-Old-Data deserialization and includes custom converters from CBOR objects to certain data types. Can be null.pod- Specifies options for controlling deserialization of CBOR objects.- Returns:
- An object of the given type decoded from the given byte array.
Returns null (as opposed to CBORObject.Null) if
datais empty and the AllowEmpty property is set on the given CBOREncodeOptions object. - Throws:
CBORException- There was an error in reading or parsing the data. This includes cases where not all of the byte array represents a CBOR object. This exception is also thrown if the parameterdatais empty unless the AllowEmpty property is set on the given options object. Also thrown if the given typet, or this object's CBOR type, is not supported, or the given object's nesting is too deep, or another error occurred when serializing the object.NullPointerException- The parameterdatais null, or the parametertorpodis null.
-
DecodeObjectFromBytes
Generates an object of an arbitrary type from an array of CBOR-encoded bytes. It is equivalent to DecodeFromBytes followed by ToObject. See the documentation for those methods for more information.- Parameters:
data- A byte array in which a single CBOR object is encoded.t-The type, class, or interface that this method's return value will belong to. To express a generic type in Java, see the example. Note: For security reasons, an application should not base this parameter on user input or other externally supplied data. Whenever possible, this parameter should be either a type specially handled by this method, such as
intorstring, or a plain-old-data type (POCO or POJO type) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.- Returns:
- An object of the given type decoded from the given byte array.
Returns null (as opposed to CBORObject.Null) if
datais empty and the AllowEmpty property is set on the given CBOREncodeOptions object. - Throws:
CBORException- There was an error in reading or parsing the data. This includes cases where not all of the byte array represents a CBOR object. This exception is also thrown if the parameterdatais empty unless the AllowEmpty property is set on the given options object. Also thrown if the given typet, or this object's CBOR type, is not supported, or the given object's nesting is too deep, or another error occurred when serializing the object.NullPointerException- The parameterdatais null, or the parametertis null.
-
FromObject
Generates a CBOR object from a 64-bit signed integer.- Parameters:
value- The parametervalueis a 64-bit signed integer.- Returns:
- A CBOR object.
-
FromObject
Generates a CBOR object from a CBOR object.- Parameters:
value- The parametervalueis a CBOR object.- Returns:
- Same as
value, or "CBORObject.Null" isvalueis null.
-
CalcEncodedSize
public long CalcEncodedSize()Calculates the number of bytes this CBOR object takes when serialized as a byte array using theEncodeToBytes()method. This calculation assumes that integers, lengths of maps and arrays, lengths of text and byte strings, and tag numbers are encoded in their shortest form; that floating-point numbers are encoded in their shortest value-preserving form; and that no indefinite-length encodings are used.- Returns:
- The number of bytes this CBOR object takes when serialized as a byte
array using the
EncodeToBytes()method. - Throws:
CBORException- The CBOR object has an extremely deep level of nesting, including if the CBOR object is or has an array or map that includes itself.
-
FromObject
Generates a CBOR object from an arbitrary-precision integer. The CBOR object is generated as follows:
- If the number is null, returns CBORObject.Null.
- Otherwise, if the number is greater than or equal to -(2^64) and less than 2^64, the CBOR object will have the object type Integer and the appropriate value.
- Otherwise, the CBOR object will have tag 2 (zero or positive) or 3 (negative) and the appropriate value.
- Parameters:
bigintValue- An arbitrary-precision integer. Can be null.- Returns:
- The given number encoded as a CBOR object. Returns CBORObject.Null
if
bigintValueis null.
-
FromObject
Generates a CBOR object from an arbitrary-precision binary floating-point number. The CBOR object is generated as follows (this is a change in version 4.0):
- If the number is null, returns CBORObject.Null.
- Otherwise, if the number expresses infinity, not-a-number, or negative zero, the CBOR object will have tag 269 and the appropriate format.
- Otherwise, if the number's exponent is at least 2^64 or less than -(2^64), the CBOR object will have tag 265 and the appropriate format.
- Otherwise, the CBOR object will have tag 5 and the appropriate format.
- Parameters:
bigValue- An arbitrary-precision binary floating-point number. Can be null.- Returns:
- The given number encoded as a CBOR object. Returns CBORObject.Null
if
bigValueis null.
-
FromObject
Generates a CBOR object from an arbitrary-precision rational number. The CBOR object is generated as follows (this is a change in version 4.0):
- If the number is null, returns CBORObject.Null.
- Otherwise, if the number expresses infinity, not-a-number, or negative zero, the CBOR object will have tag 270 and the appropriate format.
- Otherwise, the CBOR object will have tag 30 and the appropriate format.
- Parameters:
bigValue- An arbitrary-precision rational number. Can be null.- Returns:
- The given number encoded as a CBOR object. Returns CBORObject.Null
if
bigValueis null.
-
FromObject
Generates a CBOR object from a decimal number. The CBOR object is generated as follows (this is a change in version 4.0):
- If the number is null, returns CBORObject.Null.
- Otherwise, if the number expresses infinity, not-a-number, or negative zero, the CBOR object will have tag 268 and the appropriate format.
- If the number's exponent is at least 2^64 or less than -(2^64), the CBOR object will have tag 264 and the appropriate format.
- Otherwise, the CBOR object will have tag 4 and the appropriate format.
- Parameters:
bigValue- An arbitrary-precision decimal number. Can be null.- Returns:
- The given number encoded as a CBOR object. Returns CBORObject.Null
if
bigValueis null.
-
FromObject
Generates a CBOR object from a text string.- Parameters:
strValue- A text string value. Can be null.- Returns:
- A CBOR object representing the string, or CBORObject.Null if stringValue is null.
- Throws:
IllegalArgumentException- The string contains an unpaired surrogate code point.
-
FromObject
Generates a CBOR object from a 32-bit signed integer.- Parameters:
value- The parametervalueis a 32-bit signed integer.- Returns:
- A CBOR object.
-
FromObject
Generates a CBOR object from a 16-bit signed integer.- Parameters:
value- The parametervalueis a 16-bit signed integer.- Returns:
- A CBOR object generated from the given integer.
-
FromObject
Returns the CBOR true value or false value, depending on "value".- Parameters:
value- Eithertrueorfalse.- Returns:
- CBORObject.True if value is true; otherwise CBORObject.False.
-
FromObject
Generates a CBOR object from a byte (0 to 255).- Parameters:
value- The parametervalueis a byte (from 0 to 255).- Returns:
- A CBOR object generated from the given integer.
-
FromObject
Generates a CBOR object from a 32-bit floating-point number. The input value can be a not-a-number (NaN) value (such asFloat.NaNin DotNet or Float.NaN in Java); however, NaN values have multiple forms that are equivalent for many applications' purposes, andFloat.NaN/Float.NaNis only one of these equivalent forms. In fact,CBORObject.FromObject(Float.NaN)orCBORObject.FromObject(Float.NaN)could produce a CBOR-encoded object that differs between DotNet and Java, becauseFloat.NaN/Float.NaNmay have a different form in DotNet and Java (for example, the NaN value's sign may be negative in DotNet, but positive in Java).- Parameters:
value- The parametervalueis a 32-bit floating-point number.- Returns:
- A CBOR object generated from the given number.
-
FromObject
Generates a CBOR object from a 64-bit floating-point number. The input value can be a not-a-number (NaN) value (such asDouble.NaN); however, NaN values have multiple forms that are equivalent for many applications' purposes, andDouble.NaNis only one of these equivalent forms. In fact,CBORObject.FromObject(Double.NaN)could produce a CBOR-encoded object that differs between DotNet and Java, becauseDouble.NaNmay have a different form in DotNet and Java (for example, the NaN value's sign may be negative in DotNet, but positive in Java).- Parameters:
value- The parametervalueis a 64-bit floating-point number.- Returns:
- A CBOR object generated from the given number.
-
FromObject
Generates a CBOR object from an array of 8-bit bytes; the byte array is copied to a new byte array in this process. (This method can't be used to decode CBOR data from a byte array; for that, use the DecodeFromBytes method instead.).
- Parameters:
bytes- An array of 8-bit bytes; can be null.- Returns:
- A CBOR object where each element of the given byte array is copied to a new array, or CBORObject.Null if the value is null.
-
FromObject
Generates a CBOR object from an array of CBOR objects.- Parameters:
array- An array of CBOR objects.- Returns:
- A CBOR object where each element of the given array is copied to a new array, or CBORObject.Null if the value is null.
-
FromObject
Generates a CBOR object from an array of 32-bit integers.- Parameters:
array- An array of 32-bit integers.- Returns:
- A CBOR array object where each element of the given array is copied to a new array, or CBORObject.Null if the value is null.
-
FromObject
Generates a CBOR object from an array of 64-bit integers.- Parameters:
array- An array of 64-bit integers.- Returns:
- A CBOR array object where each element of the given array is copied to a new array, or CBORObject.Null if the value is null.
-
FromObject
Generates a CBORObject from an arbitrary object. See the overload of this method that takes CBORTypeMapper and PODOptions arguments.- Parameters:
obj-The parameter
objis an arbitrary object, which can be null.NOTE: For security reasons, whenever possible, an application should not base this parameter on user input or other externally supplied data unless the application limits this parameter's inputs to types specially handled by this method (such as
.intorstring) and/or to plain-old-data types (POCO or POJO types) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.- Returns:
- A CBOR object corresponding to the given object. Returns CBORObject.Null if the object is null.
-
FromObject
Generates a CBORObject from an arbitrary object. See the overload of this method that takes CBORTypeMapper and PODOptions arguments.- Parameters:
obj-The parameter
objis an arbitrary object.NOTE: For security reasons, whenever possible, an application should not base this parameter on user input or other externally supplied data unless the application limits this parameter's inputs to types specially handled by this method (such as
.intorstring) and/or to plain-old-data types (POCO or POJO types) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.options- An object containing options to control how certain objects are converted to CBOR objects.- Returns:
- A CBOR object corresponding to the given object. Returns CBORObject.Null if the object is null.
- Throws:
NullPointerException- The parameteroptionsis null.
-
FromObject
Generates a CBORObject from an arbitrary object. See the overload of this method that takes CBORTypeMapper and PODOptions arguments.- Parameters:
obj-The parameter
objis an arbitrary object.NOTE: For security reasons, whenever possible, an application should not base this parameter on user input or other externally supplied data unless the application limits this parameter's inputs to types specially handled by this method (such as
.intorstring) and/or to plain-old-data types (POCO or POJO types) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.mapper- An object containing optional converters to convert objects of certain types to CBOR objects.- Returns:
- A CBOR object corresponding to the given object. Returns CBORObject.Null if the object is null.
- Throws:
NullPointerException- The parametermapperis null.
-
FromObject
Generates a CBORObject from an arbitrary object, using the given options to control how certain objects are converted to CBOR objects. The following cases are checked in the logical order given (rather than the strict order in which they are implemented by this library):
-
nullis converted toCBORObject.Null. - A
CBORObjectis returned as itself. - If the object is of a type corresponding to a
type converter mentioned in the
mapperparameter, that converter will be used to convert the object to a CBOR object. Type converters can be used to override the default conversion behavior of almost any object. - A
charis converted to an integer (from 0 through 65535), and returns a CBOR object of that integer. (This is a change in version 4.0 from previous versions, which convertedchar, except surrogate code points from 0xd800 through 0xdfff, into single-character text strings.) - A
boolean(booleanin Java) is converted toCBORObject.TrueorCBORObject.False. - A
byteis converted to a CBOR integer from 0 through 255. - A primitive
integer type (
int,short,long, as well assbyte,ushort,uint, andulongin.NET) is converted to the corresponding CBOR integer. - A primitive
floating-point type (
float,double, as well asdecimalin.NET) is converted to the corresponding CBOR number. - A
stringis converted to a CBOR text string. To create a CBOR byte string object fromstring, see the example given incom.upokecenter.cbor.CBORObject.FromObject(System.Byte[]). - In
the.NET version, a nullable is converted to
CBORObject.Nullif the nullable's value isnull, or converted according to the nullable's underlying type, if that type is supported by this method. - In the
Java version, a number of type
BigIntegerorBigDecimalis converted to the corresponding CBOR number. - A number of type
EDecimal,EFloat,EInteger, andERationalin thePeterO.Numberslibrary (in .NET) or thecom.github.peteroupc/numbersartifact (in Java) is converted to the corresponding CBOR number. - An array other than
byte[]is converted to a CBOR array. In the.NET version, a multidimensional array is converted to an array of arrays. - A
byte[](1-dimensional byte array) is converted to a CBOR byte string; the byte array is copied to a new byte array in this process. (This method can't be used to decode CBOR data from a byte array; for that, use the DecodeFromBytes method instead.) - An object implementing Map (Map in Java) is converted to a CBOR map containing the keys and values enumerated.
- An object implementing Iterable (Iterable in Java) is converted to a CBOR array containing the items enumerated.
- An enumeration (
Enum) object is converted to its underlying value in the.NET version, or the result of itsordinal()method in the Java version. - An
object of type
java.util.Date,java.net.URI, orjava.util.UUID(Date,URI, orUUID, respectively, in Java) will be converted to a tagged CBOR object of the appropriate kind. By default,java.util.Date/Datewill be converted to a tag-0 string following the date format used in the Atom syndication format, but this behavior can be changed by passing a suitable CBORTypeMapper to this method, such as a CBORTypeMapper that registers a CBORDateConverter forjava.util.DateorDateobjects. See the examples. - If the object
is a type not specially handled above, this method checks the
objparameter for eligible getters as follows: - (*) In the .NET version,
eligible getters are the public, nonstatic getters of read/write properties
(and also those of read-only properties in the case of a compiler-generated
type or an F# type). Eligible getters also include public, nonstatic, non-
static final, non-readonlyfields. If a class has two properties and/or fields of the form "X" and "IsX", where "X" is any name, or has multiple properties and/or fields with the same name, those properties and fields are ignored. - (*) In the Java version, eligible getters are public, nonstatic methods starting with "get" or "is" (either word followed by a character other than a basic digit or lower-case letter, that is, other than "a" to "z" or "0" to "9"), that take no parameters and do not return void, except that methods named "getClass" are not eligible getters. In addition, public, nonstatic, nonfinal fields are also eligible getters. If a class has two otherwise eligible getters (methods and/or fields) of the form "isX" and "getX", where "X" is the same in both, or two such getters with the same name but different return type, they are not eligible getters.
- Then, the method returns a CBOR map with each eligible
getter's name or property name as each key, and with the corresponding value
returned by that getter as that key's value. Before adding a key-value pair
to the map, the key's name is adjusted according to the rules described in
the
PODOptionsdocumentation. Note that for security reasons, certain types are not supported even if they contain eligible getters.
REMARK: .NET enumeration (
Enum) constants could also have been converted to text strings withtoString(), but that method will return multiple names if the given Enum object is a combination of Enum objects (e.g. if the object isFileAccess.Read | FileAccess.Write). More generally, if Enums are converted to text strings, constants from Enum types with theFlagsattribute, and constants from the same Enum type that share an underlying value, should not be passed to this method.The following example (originally written in C# for the DotNet version) uses a CBORTypeMapper to change how java.util.Date objects are converted to CBOR. In this case, such objects are converted to CBOR objects with tag 1 that store numbers giving the number of seconds since the start of 1970.
CBORTypeMapper conv = new CBORTypeMapper().AddConverter(java.util.Date.class, CBORDateConverter.TaggedNumber); CBORObject obj = CBORObject.FromObject(java.util.Date.Now, conv);
The following example generates a CBOR object from a 64-bit signed integer that is treated as a 64-bit unsigned integer (such as DotNet's UInt64, which has no direct equivalent in the Java language), in the sense that the value is treated as 2^64 plus the original value if it's negative.
long x = -40L; /* Example 64-bit value treated as 2^64-40.*/ CBORObject obj = CBORObject.FromObject(v < 0 ? EInteger.FromInt32(1).ShiftLeft(64).Add(v) : EInteger.FromInt64(v));
In the Java version, which has java.math.getBigInteger(), the following can be used instead:
long x = -40L; /* Example 64-bit value treated as 2^64-40.*/ CBORObject obj = CBORObject.FromObject(v < 0 ? BigInteger.valueOf(1).shiftLeft(64).add(BigInteger.valueOf(v)) : BigInteger.valueOf(v));
- Parameters:
obj-An arbitrary object to convert to a CBOR object.
NOTE: For security reasons, whenever possible, an application should not base this parameter on user input or other externally supplied data unless the application limits this parameter's inputs to types specially handled by this method (such as
.intorstring) and/or to plain-old-data types (POCO or POJO types) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.mapper- An object containing optional converters to convert objects of certain types to CBOR objects. Can be null.options- An object containing options to control how certain objects are converted to CBOR objects.- Returns:
- A CBOR object corresponding to the given object. Returns CBORObject.Null if the object is null.
- Throws:
NullPointerException- The parameteroptionsis null.CBORException- An error occurred while converting the given object to a CBOR object.
-
-
WithTag
Generates a CBOR object from this one, but gives the resulting object a tag in addition to its existing tags (the new tag is made the outermost tag).- Parameters:
bigintTag-Tag number. The tag number 55799 can be used to mark a "self-described CBOR" object. This document does not attempt to list all CBOR tags and their meanings. An up-to-date list can be found at the CBOR Tags registry maintained by the Internet Assigned Numbers Authority( iana.org/assignments/cbor-tags).
- Returns:
- A CBOR object with the same value as this one but given the tag
bigintTagin addition to its existing tags (the new tag is made the outermost tag). - Throws:
IllegalArgumentException- The parameterbigintTagis less than 0 or greater than 2^64-1.NullPointerException- The parameterbigintTagis null.
-
FromObjectAndTag
public static CBORObject FromObjectAndTag(Object valueOb, com.upokecenter.numbers.EInteger bigintTag) Generates a CBOR object from an arbitrary object and gives the resulting object a tag in addition to its existing tags (the new tag is made the outermost tag).- Parameters:
valueOb-The parameter
valueObis an arbitrary object, which can be null.NOTE: For security reasons, whenever possible, an application should not base this parameter on user input or other externally supplied data unless the application limits this parameter's inputs to types specially handled by this method (such as
.intorstring) and/or to plain-old-data types (POCO or POJO types) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.bigintTag-Tag number. The tag number 55799 can be used to mark a "self-described CBOR" object. This document does not attempt to list all CBOR tags and their meanings. An up-to-date list can be found at the CBOR Tags registry maintained by the Internet Assigned Numbers Authority( iana.org/assignments/cbor-tags).
- Returns:
- A CBOR object where the object
valueObis converted to a CBOR object and given the tagbigintTag. IfvalueObis null, returns a version of CBORObject.Null with the given tag. - Throws:
IllegalArgumentException- The parameterbigintTagis less than 0 or greater than 2^64-1.NullPointerException- The parameterbigintTagis null.
-
WithTag
Generates a CBOR object from an arbitrary object and gives the resulting object a tag in addition to its existing tags (the new tag is made the outermost tag).- Parameters:
smallTag-A 32-bit integer that specifies a tag number. The tag number 55799 can be used to mark a "self-described CBOR" object. This document does not attempt to list all CBOR tags and their meanings. An up-to-date list can be found at the CBOR Tags registry maintained by the Internet Assigned Numbers Authority (iana.org/assignments/cbor-tags ).
- Returns:
- A CBOR object with the same value as this one but given the tag
smallTagin addition to its existing tags (the new tag is made the outermost tag). - Throws:
IllegalArgumentException- The parametersmallTagis less than 0.
-
FromObjectAndTag
Generates a CBOR object from an arbitrary object and gives the resulting object a tag in addition to its existing tags (the new tag is made the outermost tag).- Parameters:
valueObValue-The parameter
valueObValueis an arbitrary object, which can be null.NOTE: For security reasons, whenever possible, an application should not base this parameter on user input or other externally supplied data unless the application limits this parameter's inputs to types specially handled by this method (such as
.intorstring) and/or to plain-old-data types (POCO or POJO types) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.smallTag-A 32-bit integer that specifies a tag number. The tag number 55799 can be used to mark a "self-described CBOR" object. This document does not attempt to list all CBOR tags and their meanings. An up-to-date list can be found at the CBOR Tags registry maintained by the Internet Assigned Numbers Authority (iana.org/assignments/cbor-tags ).
- Returns:
- A CBOR object where the object
valueObValueis converted to a CBOR object and given the tagsmallTag. If "valueOb" is null, returns a version of CBORObject.Null with the given tag. - Throws:
IllegalArgumentException- The parametersmallTagis less than 0.
-
FromSimpleValue
Creates a CBOR object from a simple value number.- Parameters:
simpleValue- The parametersimpleValueis a 32-bit signed integer.- Returns:
- A CBOR object.
- Throws:
IllegalArgumentException- The parametersimpleValueis less than 0, greater than 255, or from 24 through 31.
-
Multiply
Deprecated.Instead, convert both CBOR objects to numbers (with .AsNumber()), and use the first number's.Multiply() method.Multiplies two CBOR numbers.- Parameters:
first- The parameterfirstis a CBOR object.second- The parametersecondis a CBOR object.- Returns:
- The product of the two numbers.
- Throws:
IllegalArgumentException- Either or both operands are not numbers (as opposed to Not-a-Number, NaN).NullPointerException- The parameterfirstorsecondis null.
-
NewArray
Creates a new empty CBOR array.- Returns:
- A new CBOR array.
-
NewMap
Creates a new empty CBOR map that stores its keys in an undefined order.- Returns:
- A new CBOR map.
-
NewOrderedMap
Creates a new empty CBOR map that ensures that keys are stored in the order in which they are first inserted.- Returns:
- A new CBOR map.
-
ReadSequence
Reads a sequence of objects in CBOR format from a data stream. This method will read CBOR objects from the stream until the end of the stream is reached or an error occurs, whichever happens first.- Parameters:
stream- A readable data stream.- Returns:
- An array containing the CBOR objects that were read from the data stream. Returns an empty array if there is no unread data in the stream.
- Throws:
NullPointerException- The parameterstreamis null, or the parameter "options" is null.CBORException- There was an error in reading or parsing the data, including if the last CBOR object was read only partially.IOException
-
ReadSequence
public static CBORObject[] ReadSequence(InputStream stream, CBOREncodeOptions options) throws IOException Reads a sequence of objects in CBOR format from a data stream. This method will read CBOR objects from the stream until the end of the stream is reached or an error occurs, whichever happens first.- Parameters:
stream- A readable data stream.options- Specifies the options to use when decoding the CBOR data stream. See CBOREncodeOptions for more information. In this method, the AllowEmpty property is treated as set regardless of the value of that property specified in this parameter.- Returns:
- An array containing the CBOR objects that were read from the data stream. Returns an empty array if there is no unread data in the stream.
- Throws:
NullPointerException- The parameterstreamis null, or the parameteroptionsis null.CBORException- There was an error in reading or parsing the data, including if the last CBOR object was read only partially.IOException
-
Read
Reads an object in CBOR format from a data stream. This method will read from the stream until the end of the CBOR object is reached or an error occurs, whichever happens first.- Parameters:
stream- A readable data stream.- Returns:
- A CBOR object that was read.
- Throws:
NullPointerException- The parameterstreamis null.CBORException- There was an error in reading or parsing the data.
-
Read
Reads an object in CBOR format from a data stream, using the specified options to control the decoding process. This method will read from the stream until the end of the CBOR object is reached or an error occurs, whichever happens first.- Parameters:
stream- A readable data stream.options- Specifies the options to use when decoding the CBOR data stream. See CBOREncodeOptions for more information.- Returns:
- A CBOR object that was read.
- Throws:
NullPointerException- The parameterstreamis null.CBORException- There was an error in reading or parsing the data.
-
ReadJSON
Generates a CBOR object from a data stream in JavaScript object Notation (JSON) format. The JSON stream may begin with a byte-order mark (U+FEFF). Since version 2.0, the JSON stream can be in UTF-8, UTF-16, or UTF-32 encoding; the encoding is detected by assuming that the first character read must be a byte-order mark or a nonzero basic character (U+0001 to U+007F). (In previous versions, only UTF-8 was allowed.). (This behavior may change to supporting only UTF-8, with or without a byte order mark, in version 5.0 or later, perhaps with an option to restore the previous behavior of also supporting UTF-16 and UTF-32.).- Parameters:
stream- A readable data stream. The sequence of bytes read from the data stream must contain a single JSON object and not multiple objects.- Returns:
- A CBOR object.
- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.CBORException- The data stream contains invalid encoding or is not in JSON format.
-
ReadJSONSequence
Generates a list of CBOR objects from a data stream in JavaScript object Notation (JSON) text sequence format (RFC 7464). The data stream must be in UTF-8 encoding and may not begin with a byte-order mark (U+FEFF).
Generally, each JSON text in a JSON text sequence is written as follows: Write a record separator byte (0x1e), then write the JSON text in UTF-8 (without a byte order mark, U+FEFF), then write the line feed byte (0x0a). RFC 7464, however, uses a more liberal syntax for parsing JSON text sequences.
- Parameters:
stream- A readable data stream. The sequence of bytes read from the data stream must either be empty or begin with a record separator byte (0x1e).- Returns:
- A list of CBOR objects read from the JSON sequence. Objects that
could not be parsed are replaced with
null(as opposed toCBORObject.Null) in the given list. - Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.CBORException- The data stream is not empty and does not begin with a record separator byte (0x1e).
-
ReadJSON
@Deprecated public static CBORObject ReadJSON(InputStream stream, CBOREncodeOptions options) throws IOException Deprecated.Instead, use.getReadJSON()(stream, new JSONOptions(\allowduplicatekeys = true\)) or .getReadJSON()(stream, new JSONOptions(\allowduplicatekeys = false\)), as appropriate.Generates a CBOR object from a data stream in JavaScript object Notation (JSON) format, using the specified options to control the decoding process. The JSON stream may begin with a byte-order mark (U+FEFF). Since version 2.0, the JSON stream can be in UTF-8, UTF-16, or UTF-32 encoding; the encoding is detected by assuming that the first character read must be a byte-order mark or a nonzero basic character (U+0001 to U+007F). (In previous versions, only UTF-8 was allowed.).- Parameters:
stream- A readable data stream. The sequence of bytes read from the data stream must contain a single JSON object and not multiple objects.options- Contains options to control the JSON decoding process. This method uses only the AllowDuplicateKeys property of this object.- Returns:
- A CBOR object containing the JSON data decoded.
- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.CBORException- The data stream contains invalid encoding or is not in JSON format.
-
ReadJSONSequence
public static CBORObject[] ReadJSONSequence(InputStream stream, JSONOptions jsonoptions) throws IOException Generates a list of CBOR objects from a data stream in JavaScript object Notation (JSON) text sequence format (RFC 7464). The data stream must be in UTF-8 encoding and may not begin with a byte-order mark (U+FEFF).
Generally, each JSON text in a JSON text sequence is written as follows: Write a record separator byte (0x1e), then write the JSON text in UTF-8 (without a byte order mark, U+FEFF), then write the line feed byte (0x0a). RFC 7464, however, uses a more liberal syntax for parsing JSON text sequences.
- Parameters:
stream- A readable data stream. The sequence of bytes read from the data stream must either be empty or begin with a record separator byte (0x1e).jsonoptions- Specifies options to control how JSON texts in the stream are decoded to CBOR. See the JSONOptions class.- Returns:
- A list of CBOR objects read from the JSON sequence. Objects that
could not be parsed are replaced with
null(as opposed toCBORObject.Null) in the given list. - Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.CBORException- The data stream is not empty and does not begin with a record separator byte (0x1e).
-
ReadJSON
Generates a CBOR object from a data stream in JavaScript object Notation (JSON) format, using the specified options to control the decoding process. The JSON stream may begin with a byte-order mark (U+FEFF). Since version 2.0, the JSON stream can be in UTF-8, UTF-16, or UTF-32 encoding; the encoding is detected by assuming that the first character read must be a byte-order mark or a nonzero basic character (U+0001 to U+007F). (In previous versions, only UTF-8 was allowed.). (This behavior may change to supporting only UTF-8, with or without a byte order mark, in version 5.0 or later, perhaps with an option to restore the previous behavior of also supporting UTF-16 and UTF-32.).- Parameters:
stream- A readable data stream. The sequence of bytes read from the data stream must contain a single JSON object and not multiple objects.jsonoptions- Specifies options to control how the JSON stream is decoded to CBOR. See the JSONOptions class.- Returns:
- A CBOR object containing the JSON data decoded.
- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.CBORException- The data stream contains invalid encoding or is not in JSON format.
-
FromJSONBytes
Generates a CBOR object from a byte array in JavaScript object Notation (JSON) format.
If a JSON object has duplicate keys, a CBORException is thrown.
Note that if a CBOR object is converted to JSON with
ToJSONBytes, then the JSON is converted back to CBOR with this method, the new CBOR object will not necessarily be the same as the old CBOR object, especially if the old CBOR object uses data types not supported in JSON, such as integers in map keys.- Parameters:
bytes- A byte array in JSON format. The entire byte array must contain a single JSON object and not multiple objects. The byte array may begin with a byte-order mark (U+FEFF). The byte array can be in UTF-8, UTF-16, or UTF-32 encoding; the encoding is detected by assuming that the first character read must be a byte-order mark or a nonzero basic character (U+0001 to U+007F). (This behavior may change to supporting only UTF-8, with or without a byte order mark, in version 5.0 or later, perhaps with an option to restore the previous behavior of also supporting UTF-16 and UTF-32.).- Returns:
- A CBOR object containing the JSON data decoded.
- Throws:
NullPointerException- The parameterbytesis null.CBORException- The byte array contains invalid encoding or is not in JSON format.
-
FromJSONBytes
Generates a CBOR object from a byte array in JavaScript object Notation (JSON) format, using the specified options to control the decoding process.
Note that if a CBOR object is converted to JSON with
ToJSONBytes, then the JSON is converted back to CBOR with this method, the new CBOR object will not necessarily be the same as the old CBOR object, especially if the old CBOR object uses data types not supported in JSON, such as integers in map keys.- Parameters:
bytes- A byte array in JSON format. The entire byte array must contain a single JSON object and not multiple objects. The byte array may begin with a byte-order mark (U+FEFF). The byte array can be in UTF-8, UTF-16, or UTF-32 encoding; the encoding is detected by assuming that the first character read must be a byte-order mark or a nonzero basic character (U+0001 to U+007F). (This behavior may change to supporting only UTF-8, with or without a byte order mark, in version 5.0 or later, perhaps with an option to restore the previous behavior of also supporting UTF-16 and UTF-32.).jsonoptions- Specifies options to control how the JSON data is decoded to CBOR. See the JSONOptions class.- Returns:
- A CBOR object containing the JSON data decoded.
- Throws:
NullPointerException- The parameterbytesorjsonoptionsis null.CBORException- The byte array contains invalid encoding or is not in JSON format.
-
FromJSONBytes
Generates a CBOR object from a byte array in JavaScript object Notation (JSON) format.
If a JSON object has duplicate keys, a CBORException is thrown.
Note that if a CBOR object is converted to JSON with
ToJSONBytes, then the JSON is converted back to CBOR with this method, the new CBOR object will not necessarily be the same as the old CBOR object, especially if the old CBOR object uses data types not supported in JSON, such as integers in map keys.- Parameters:
bytes- A byte array, the specified portion of which is in JSON format. The specified portion of the byte array must contain a single JSON object and not multiple objects. The portion may begin with a byte-order mark (U+FEFF). The portion can be in UTF-8, UTF-16, or UTF-32 encoding; the encoding is detected by assuming that the first character read must be a byte-order mark or a nonzero basic character (U+0001 to U+007F). (This behavior may change to supporting only UTF-8, with or without a byte order mark, in version 5.0 or later, perhaps with an option to restore the previous behavior of also supporting UTF-16 and UTF-32.).offset- An index, starting at 0, showing where the desired portion ofbytesbegins.count- The length, in bytes, of the desired portion ofbytes(but not more thanbytes's length).- Returns:
- A CBOR object containing the JSON data decoded.
- Throws:
NullPointerException- The parameterbytesis null.CBORException- The byte array contains invalid encoding or is not in JSON format.IllegalArgumentException- Eitheroffsetorcountis less than 0 or greater thanbytes's length, orbytes's length minusoffsetis less thancount.
-
FromJSONBytes
public static CBORObject FromJSONBytes(byte[] bytes, int offset, int count, JSONOptions jsonoptions) Generates a CBOR object from a byte array in JavaScript object Notation (JSON) format, using the specified options to control the decoding process.
Note that if a CBOR object is converted to JSON with
ToJSONBytes, then the JSON is converted back to CBOR with this method, the new CBOR object will not necessarily be the same as the old CBOR object, especially if the old CBOR object uses data types not supported in JSON, such as integers in map keys.- Parameters:
bytes- A byte array, the specified portion of which is in JSON format. The specified portion of the byte array must contain a single JSON object and not multiple objects. The portion may begin with a byte-order mark (U+FEFF). The portion can be in UTF-8, UTF-16, or UTF-32 encoding; the encoding is detected by assuming that the first character read must be a byte-order mark or a nonzero basic character (U+0001 to U+007F). (This behavior may change to supporting only UTF-8, with or without a byte order mark, in version 5.0 or later, perhaps with an option to restore the previous behavior of also supporting UTF-16 and UTF-32.).offset- An index, starting at 0, showing where the desired portion ofbytesbegins.count- The length, in bytes, of the desired portion ofbytes(but not more thanbytes's length).jsonoptions- Specifies options to control how the JSON data is decoded to CBOR. See the JSONOptions class.- Returns:
- A CBOR object containing the JSON data decoded.
- Throws:
NullPointerException- The parameterbytesorjsonoptionsis null.CBORException- The byte array contains invalid encoding or is not in JSON format.IllegalArgumentException- Eitheroffsetorcountis less than 0 or greater thanbytes's length, orbytes's length minusoffsetis less thancount.
-
Remainder
Deprecated.Instead, convert both CBOR objects to numbers (with .AsNumber()), and use the first number's.Remainder() method.Finds the remainder that results when a CBORObject object is divided by the value of a CBOR object.- Parameters:
first- The parameterfirstis a CBOR object.second- The parametersecondis a CBOR object.- Returns:
- The remainder of the two numbers.
- Throws:
NullPointerException- The parameterfirstorsecondis null.
-
Subtract
Deprecated.Instead, convert both CBOR objects to numbers (with .AsNumber()), and use the first number's.Subtract() method.Finds the difference between two CBOR number objects.- Parameters:
first- The parameterfirstis a CBOR object.second- The parametersecondis a CBOR object.- Returns:
- The difference of the two objects.
- Throws:
IllegalArgumentException- Either or both operands are not numbers (as opposed to Not-a-Number, NaN).NullPointerException- The parameterfirstorsecondis null.
-
Write
Writes a text string in CBOR format to a data stream. The string will be encoded using definite-length encoding regardless of its length.- Parameters:
str- The string to write. Can be null.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
public static void Write(String str, OutputStream stream, CBOREncodeOptions options) throws IOException Writes a text string in CBOR format to a data stream, using the given options to control the encoding process.- Parameters:
str- The string to write. Can be null.stream- A writable data stream.options- Options for encoding the data to CBOR.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
public static void Write(com.upokecenter.numbers.EFloat bignum, OutputStream stream) throws IOException Writes a binary floating-point number in CBOR format to a data stream, as though it were converted to a CBOR object via CBORObject.FromObject(EFloat) and then written out.- Parameters:
bignum- An arbitrary-precision binary floating-point number. Can be null.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
public static void Write(com.upokecenter.numbers.ERational rational, OutputStream stream) throws IOException Writes a rational number in CBOR format to a data stream, as though it were converted to a CBOR object via CBORObject.FromObject(ERational) and then written out.- Parameters:
rational- An arbitrary-precision rational number. Can be null.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
public static void Write(com.upokecenter.numbers.EDecimal bignum, OutputStream stream) throws IOException Writes a decimal floating-point number in CBOR format to a data stream, as though it were converted to a CBOR object via CBORObject.FromObject(EDecimal) and then written out.- Parameters:
bignum- The arbitrary-precision decimal number to write. Can be null.stream- InputStream to write to.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
public static void Write(com.upokecenter.numbers.EInteger bigint, OutputStream stream) throws IOException Writes a arbitrary-precision integer in CBOR format to a data stream.- Parameters:
bigint- Arbitrary-precision integer to write. Can be null.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
Writes a 64-bit signed integer in CBOR format to a data stream.- Parameters:
value- The value to write.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
Writes a 32-bit signed integer in CBOR format to a data stream.- Parameters:
value- The value to write.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
Writes a 16-bit signed integer in CBOR format to a data stream.- Parameters:
value- The value to write.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
Writes a Boolean value in CBOR format to a data stream.- Parameters:
value- The value to write.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
Writes a byte (0 to 255) in CBOR format to a data stream. If the value is less than 24, writes that byte. If the value is 25 to 255, writes the byte 24, then this byte's value.- Parameters:
value- The value to write.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
Writes a 32-bit floating-point number in CBOR format to a data stream. The number is written using the shortest floating-point encoding possible; this is a change from previous versions.- Parameters:
value- The value to write.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
Writes a 64-bit floating-point number in CBOR format to a data stream. The number is written using the shortest floating-point encoding possible; this is a change from previous versions.- Parameters:
value- The value to write.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
Write
Writes a CBOR object to a CBOR data stream.- Parameters:
value- The value to write. Can be null.stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException
-
Write
Writes a CBOR object to a CBOR data stream. See the three-parameter Write method that takes a CBOREncodeOptions.- Parameters:
objValue- The arbitrary object to be serialized. Can be null.stream- A writable data stream.- Throws:
IOException
-
Write
public static void Write(Object objValue, OutputStream output, CBOREncodeOptions options) throws IOException Writes an arbitrary object to a CBOR data stream, using the specified options for controlling how the object is encoded to CBOR data format. If the object is convertible to a CBOR map or a CBOR object that contains CBOR maps, the order in which the keys to those maps are written out to the data stream is undefined unless the map was created using the NewOrderedMap method. The example code given in
com.upokecenter.cbor.CBORObject.WriteTo(System.IO.InputStream)can be used to write out certain keys of a CBOR map in a given order. Currently, the following objects are supported:- Lists of CBORObject.
- Maps of CBORObject. The order in which the keys to the map are written out to the data stream is undefined unless the map was created using the NewOrderedMap method.
- Null.
- Byte arrays, which will always be written as definite-length byte strings.
- string objects. The strings will be encoded using definite-length encoding regardless of their length.
- Any object accepted by the FromObject static methods.
- Parameters:
objValue-The arbitrary object to be serialized. Can be null.
NOTE: For security reasons, whenever possible, an application should not base this parameter on user input or other externally supplied data unless the application limits this parameter's inputs to types specially handled by this method (such as
.intorstring) and/or to plain-old-data types (POCO or POJO types) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.output- A writable data stream.options- CBOR options for encoding the CBOR object to bytes.- Throws:
IllegalArgumentException- The object's type is not supported.NullPointerException- The parameteroptionsoroutputis null.IOException
-
WriteJSON
Converts an arbitrary object to a text string in JavaScript object Notation (JSON) format, as in the ToJSONString method, and writes that string to a data stream in UTF-8. If the object is convertible to a CBOR map, or to a CBOR object that contains CBOR maps, the order in which the keys to those maps are written out to the JSON string is undefined unless the map was created using the NewOrderedMap method. The example code given in PeterO.Cbor.CBORObject.ToJSONString(PeterO.Cbor.JSONOptions) can be used to write out certain keys of a CBOR map in a given order to a JSON string.
- Parameters:
obj-The parameter
objis an arbitrary object. Can be null.NOTE: For security reasons, whenever possible, an application should not base this parameter on user input or other externally supplied data unless the application limits this parameter's inputs to types specially handled by this method (such as
.intorstring) and/or to plain-old-data types (POCO or POJO types) within the control of the application. If the plain-old-data type references other data types, those types should likewise meet either criterion above.outputStream- A writable data stream.- Throws:
NullPointerException- The parameteroutputStreamis null.IOException
-
Abs
Deprecated.Instead, convert this object to a number (with .getAsNumber()()), and use that number's.getAbs()() method.Gets this object's absolute value.- Returns:
- This object's absolute without its negative sign.
- Throws:
IllegalStateException- This object does not represent a number (for this purpose, infinities and not-a-number or NaN values, but not CBORObject.Null, are considered numbers).
-
Add
Adds a new key and its value to this CBOR map, or adds the value if the key doesn't exist.
NOTE: This method can't be used to add a tag to an existing CBOR object. To create a CBOR object with a given tag, call the
CBORObject.FromObjectAndTagmethod and pass the CBOR object and the desired tag number to that method.- Parameters:
key- An object representing the key, which will be converted to a CBORObject. Can be null, in which case this value is converted to CBORObject.Null.valueOb- An object representing the value, which will be converted to a CBORObject. Can be null, in which case this value is converted to CBORObject.Null.- Returns:
- This instance.
- Throws:
IllegalArgumentException- The parameterkeyalready exists in this map.IllegalStateException- This object is not a map.IllegalArgumentException- The parameterkeyorvalueObhas an unsupported type.
-
Add
Adds a new object to the end of this array. (Used to throw NullPointerException on a null reference, but now converts the null reference to CBORObject.Null, for convenience with the object overload of this method).
NOTE: This method can't be used to add a tag to an existing CBOR object. To create a CBOR object with a given tag, call the
CBORObject.FromObjectAndTagmethod and pass the CBOR object and the desired tag number to that method.The following example creates a CBOR array and adds several CBOR objects, one of which has a custom CBOR tag, to that array. Note the chaining behavior made possible by this method.
CBORObject obj = CBORObject.NewArray() .Add(CBORObject.False) .Add(CBORObject.FromObject(5)) .Add(CBORObject.FromObject("text string")) .Add(CBORObject.FromObjectAndTag(9999, 1));.- Parameters:
obj- The parameterobjis a CBOR object.- Returns:
- This instance.
- Throws:
IllegalStateException- This object is not an array.
-
Add
Converts an object to a CBOR object and adds it to the end of this array.
NOTE: This method can't be used to add a tag to an existing CBOR object. To create a CBOR object with a given tag, call the
CBORObject.FromObjectAndTagmethod and pass the CBOR object and the desired tag number to that method.The following example creates a CBOR array and adds several CBOR objects, one of which has a custom CBOR tag, to that array. Note the chaining behavior made possible by this method.
CBORObject obj = CBORObject.NewArray() .Add(CBORObject.False) .Add(5) .Add("text string") .Add(CBORObject.FromObjectAndTag(9999, 1));.- Parameters:
obj- A CBOR object (or an object convertible to a CBOR object) to add to this CBOR array.- Returns:
- This instance.
- Throws:
IllegalStateException- This instance is not an array.IllegalArgumentException- The type ofobjis not supported.
-
AsEInteger
Deprecated.Instead, use.getToObject()<PeterO.Numbers.EInteger>() in .NET or .getToObject()(com.upokecenter.numbers.EInteger.class) in Java.Converts this object to an arbitrary-precision integer. See the ToObject overload taking a type for more information.- Returns:
- The closest arbitrary-precision integer to this object.
- Throws:
IllegalStateException- This object does not represent a number (for the purposes of this method, infinity and not-a-number values, but notCBORObject.Null, are considered numbers).ArithmeticException- This object's value is infinity or not-a-number (NaN).
-
AsBoolean
public boolean AsBoolean()Returns false if this object is a CBOR false, null, or undefined value (whether or not the object has tags); otherwise, true.- Returns:
- False if this object is a CBOR false, null, or undefined value; otherwise, true.
-
AsByte
Deprecated.Instead, use.getToObject()<byte>() in .NET or .getToObject()(Byte.class) in Java.Converts this object to a byte (0 to 255). Floating point values are converted to integers by discarding their fractional parts.- Returns:
- The closest byte-sized integer to this object.
- Throws:
IllegalStateException- This object does not represent a number (for this purpose, infinities and not-a-number or NaN values, but not CBORObject.Null, are considered numbers).ArithmeticException- This object's value exceeds the range of a byte (would be less than 0 or greater than 255 when converted to an integer by discarding its fractional part).
-
AsDouble
public double AsDouble()Converts this object to a 64-bit floating point number.- Returns:
- The closest 64-bit floating point number to this object. The return value can be positive infinity or negative infinity if this value exceeds the range of a 64-bit floating point number.
- Throws:
IllegalStateException- This object does not represent a number (for this purpose, infinities and not-a-number or NaN values, but not CBORObject.Null, are considered numbers).
-
AsEDecimal
Deprecated.Instead, use.getToObject()<PeterO.Numbers.EDecimal>() in .NET or .getToObject()(com.upokecenter.numbers.EDecimal.class) in Java.Converts this object to a decimal number.- Returns:
- A decimal number for this object's value.
- Throws:
IllegalStateException- This object does not represent a number (for the purposes of this method, infinity and not-a-number values, but notCBORObject.Null, are considered numbers).
-
AsEFloat
Deprecated.Instead, use.getToObject()<PeterO.Numbers.EFloat>() in.NET or .getToObject()(com.upokecenter.numbers.EFloat.class) in Java.Converts this object to an arbitrary-precision binary floating point number. See the ToObject overload taking a type for more information.- Returns:
- An arbitrary-precision binary floating-point number for this object's value.
- Throws:
IllegalStateException- This object does not represent a number (for the purposes of this method, infinity and not-a-number values, but notCBORObject.Null, are considered numbers).
-
AsERational
Deprecated.Instead, use.getToObject()<PeterO.Numbers.ERational>() in .NET or.getToObject()(com.upokecenter.numbers.ERational.class) in Java.Converts this object to a rational number. See the ToObject overload taking a type for more information.- Returns:
- A rational number for this object's value.
- Throws:
IllegalStateException- This object does not represent a number (for the purposes of this method, infinity and not-a-number values, but notCBORObject.Null, are considered numbers).
-
AsInt16
Deprecated.Instead, use the following: (cbor.AsNumber().ToInt16Checked()), or .getToObject()<short>() in .NET.Converts this object to a 16-bit signed integer. Floating point values are converted to integers by discarding their fractional parts.- Returns:
- The closest 16-bit signed integer to this object.
- Throws:
IllegalStateException- This object does not represent a number (for this purpose, infinities and not-a-number or NaN values, but not CBORObject.Null, are considered numbers).ArithmeticException- This object's value exceeds the range of a 16-bit signed integer.
-
AsInt32Value
public int AsInt32Value()Converts this object to a 32-bit signed integer if this CBOR object's type is Integer. This method disregards the tags this object has, if any.
The following example code (originally written in C# for the.NET Framework) shows a way to check whether a given CBOR object stores a 32-bit signed integer before getting its value.
CBORObject obj = CBORObject.FromInt32(99999); if (obj.CanValueFitInInt32()) { /* Not an Int32; handle the error */ System.out.println("Not a 32-bit integer."); } else { System.out.println("The value is " + obj.AsInt32Value()); }.- Returns:
- The 32-bit signed integer stored by this object.
- Throws:
IllegalStateException- This object's type is notCBORType.Integer.ArithmeticException- This object's value exceeds the range of a 32-bit signed integer.
-
AsInt64Value
public long AsInt64Value()Converts this object to a 64-bit signed integer if this CBOR object's type is Integer. This method disregards the tags this object has, if any.
The following example code (originally written in C# for the.NET Framework) shows a way to check whether a given CBOR object stores a 64-bit signed integer before getting its value.
CBORObject obj = CBORObject.FromInt64(99999); if (obj.CanValueFitInInt64()) { /* Not an Int64; handle the error*/ System.out.println("Not a 64-bit integer."); } else { System.out.println("The value is " + obj.AsInt64Value()); }.- Returns:
- The 64-bit signed integer stored by this object.
- Throws:
IllegalStateException- This object's type is notCBORType.Integer.ArithmeticException- This object's value exceeds the range of a 64-bit signed integer.
-
CanValueFitInInt64
public boolean CanValueFitInInt64()Returns whether this CBOR object stores an integer (CBORType.Integer) within the range of a 64-bit signed integer. This method disregards the tags this object has, if any.- Returns:
trueif this CBOR object stores an integer (CBORType.Integer) whose value is at least -(2^63) and less than 2^63; otherwise,false.
-
CanValueFitInInt32
public boolean CanValueFitInInt32()Returns whether this CBOR object stores an integer (CBORType.Integer) within the range of a 32-bit signed integer. This method disregards the tags this object has, if any.- Returns:
trueif this CBOR object stores an integer (CBORType.Integer) whose value is at least -(2^31) and less than 2^31; otherwise,false.
-
AsEIntegerValue
public com.upokecenter.numbers.EInteger AsEIntegerValue()Converts this object to an arbitrary-precision integer if this CBOR object's type is Integer. This method disregards the tags this object has, if any. (Note that CBOR stores untagged integers at least -(2^64) and less than 2^64.).- Returns:
- The integer stored by this object.
- Throws:
IllegalStateException- This object's type is notCBORType.Integer.
-
AsDoubleBits
public long AsDoubleBits()Converts this object to the bits of a 64-bit floating-point number if this CBOR object's type is FloatingPoint. This method disregards the tags this object has, if any.- Returns:
- The bits of a 64-bit floating-point number stored by this object. The most significant bit is the sign (set means negative, clear means nonnegative); the next most significant 11 bits are the exponent area; and the remaining bits are the significand area. If all the bits of the exponent area are set and the significand area is 0, this indicates infinity. If all the bits of the exponent area are set and the significand area is other than 0, this indicates not-a-number (NaN).
- Throws:
IllegalStateException- This object's type is notCBORType.FloatingPoint.
-
AsDoubleValue
public double AsDoubleValue()Converts this object to a 64-bit floating-point number if this CBOR object's type is FloatingPoint. This method disregards the tags this object has, if any.- Returns:
- The 64-bit floating-point number stored by this object.
- Throws:
IllegalStateException- This object's type is notCBORType.FloatingPoint.
-
AsNumber
Converts this object to a CBOR number. (NOTE: To determine whether this method call can succeed, call the IsNumber property (isNumber() method in Java) before calling this method.).
- Returns:
- The number represented by this object.
- Throws:
IllegalStateException- This object does not represent a number (for this purpose, infinities and not-a-number or NaN values, but not CBORObject.Null, are considered numbers).
-
AsInt32
public int AsInt32()Converts this object to a 32-bit signed integer. Non-integer number values are converted to integers by discarding their fractional parts. (NOTE: To determine whether this method call can succeed, call AsNumber().getCanTruncatedIntFitInInt32() before calling this method. See the example.).
The following example code (originally written in C# for the.NET Framework) shows a way to check whether a given CBOR object stores a 32-bit signed integer before getting its value.
CBORObject obj = CBORObject.FromInt32(99999); if (obj.AsNumber().CanTruncatedIntFitInInt32()) { /* Not an Int32; handle the error */ System.out.println("Not a 32-bit integer."); } else { System.out.println("The value is " + obj.AsInt32()); }.- Returns:
- The closest 32-bit signed integer to this object.
- Throws:
IllegalStateException- This object does not represent a number (for this purpose, infinities and not-a-number or NaN values, but not CBORObject.Null, are considered numbers).ArithmeticException- This object's value exceeds the range of a 32-bit signed integer.
-
AsInt64
Deprecated.Instead, use the following: (cbor.AsNumber().ToInt64Checked()), or .ToObject<long>() in.NET.Converts this object to a 64-bit signed integer. Non-integer numbers are converted to integers by discarding their fractional parts. (NOTE: To determine whether this method call can succeed, call AsNumber().getCanTruncatedIntFitInInt64() before calling this method. See the example.).
The following example code (originally written in C# for the.NET Framework) shows a way to check whether a given CBOR object stores a 64-bit signed integer before getting its value.
CBORObject obj = CBORObject.FromInt64(99999); if (obj.isIntegral() && obj.AsNumber().CanFitInInt64()) { /* Not an Int64; handle the error */ System.out.println("Not a 64-bit integer."); } else { System.out.println("The value is " + obj.AsInt64()); }.- Returns:
- The closest 64-bit signed integer to this object.
- Throws:
IllegalStateException- This object does not represent a number (for this purpose, infinities and not-a-number or NaN values, but not CBORObject.Null, are considered numbers).ArithmeticException- This object's value exceeds the range of a 64-bit signed integer.
-
AsSingle
public float AsSingle()Converts this object to a 32-bit floating point number.- Returns:
- The closest 32-bit floating point number to this object. The return value can be positive infinity or negative infinity if this object's value exceeds the range of a 32-bit floating point number.
- Throws:
IllegalStateException- This object does not represent a number (for this purpose, infinities and not-a-number or NaN values, but not CBORObject.Null, are considered numbers).
-
AsString
Gets the value of this object as a text string.
This method is not the "reverse" of the
FromObjectmethod in the sense that FromObject can take either a text string ornull, but this method can accept only text strings. TheToObjectmethod is closer to a "reverse" version toFromObjectthan theAsStringmethod:ToObject<string>(cbor)in DotNet, orToObject(string.class)in Java, will convert a CBOR object to a DotNet or Java string if it represents a text string, or tonullifIsNullreturnstruefor the CBOR object, and will fail in other cases.- Returns:
- Gets this object's string.
- Throws:
IllegalStateException- This object's type is not a text string (for the purposes of this method, infinity and not-a-number values, but notCBORObject.Null, are considered numbers). To check the CBOR object for null before conversion, use the following idiom (originally written in C# for the.NET version):(cbor == null || cbor.isNull()) ? null : cbor.AsString().
-
CanFitInDouble
Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().CanFitInDouble()).Returns whether this object's value can be converted to a 64-bit floating point number without its value being rounded to another numerical value.- Returns:
trueif this object's value can be converted to a 64-bit floating point number without its value being rounded to another numerical value, or if this is a not-a-number value, even if the value's diagnostic information can't fit in a 64-bit floating point number; otherwise,false.
-
CanFitInInt32
Deprecated.Instead, use.CanValueFitInInt32(), if the application allows only CBOR integers, or (cbor.isNumber() &&cbor.AsNumber().CanFitInInt32()), if the application allows any CBOR Object convertible to an integer.Returns whether this object's numerical value is an integer, is -(2^31) or greater, and is less than 2^31.- Returns:
trueif this object's numerical value is an integer, is -(2^31) or greater, and is less than 2^31; otherwise,false.
-
CanFitInInt64
Deprecated.Instead, use CanValueFitInInt64(), if the application allows only CBOR integers, or (cbor.isNumber() &&cbor.AsNumber().CanFitInInt64()), if the application allows any CBOR Object convertible to an integer.Returns whether this object's numerical value is an integer, is -(2^63) or greater, and is less than 2^63.- Returns:
trueif this object's numerical value is an integer, is -(2^63) or greater, and is less than 2^63; otherwise,false.
-
CanFitInSingle
Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().CanFitInSingle()).Returns whether this object's value can be converted to a 32-bit floating point number without its value being rounded to another numerical value.- Returns:
trueif this object's value can be converted to a 32-bit floating point number without its value being rounded to another numerical value, or if this is a not-a-number value, even if the value's diagnostic information can' t fit in a 32-bit floating point number; otherwise,false.
-
CanTruncatedIntFitInInt32
Deprecated.Instead, use the following: (cbor.CanValueFitInInt32() if only integers of any tag are allowed, or (cbor.isNumber() && cbor.AsNumber().CanTruncatedIntFitInInt32()).Returns whether this object's value, converted to an integer by discarding its fractional part, would be -(2^31) or greater, and less than 2^31.- Returns:
trueif this object's value, converted to an integer by discarding its fractional part, would be -(2^31) or greater, and less than 2^31; otherwise,false.
-
CanTruncatedIntFitInInt64
Deprecated.Instead, use the following: (cbor.CanValueFitInInt64() if only integers of any tag are allowed, or (cbor.isNumber() && cbor.AsNumber().CanTruncatedIntFitInInt64()).Returns whether this object's value, converted to an integer by discarding its fractional part, would be -(2^63) or greater, and less than 2^63.- Returns:
trueif this object's value, converted to an integer by discarding its fractional part, would be -(2^63) or greater, and less than 2^63; otherwise,false.
-
compareTo
Compares two CBOR objects. This implementation was changed in version 4.0.
In this implementation:
- The null pointer (null reference) is considered less than any other object.
- If the two objects are both integers (CBORType.Integer) both floating-point values, both byte strings, both simple values (including True and False), or both text strings, their CBOR encodings (as though EncodeToBytes were called on each integer) are compared as though by a byte-by-byte comparison. (This means, for example, that positive integers sort before negative integers).
- If both objects have a tag, they are compared first by the tag's value then by the associated item (which itself can have a tag).
- If both objects are arrays, they are compared item by item. In this case, if the arrays have different numbers of items, the array with more items is treated as greater than the other array.
- If both objects are maps, their key-value pairs, sorted by key in accordance with this method, are compared, where each pair is compared first by key and then by value. In this case, if the maps have different numbers of key-value pairs, the map with more pairs is treated as greater than the other map.
- If the two objects have different types, the object whose type comes first in the order of untagged integers, untagged byte strings, untagged text strings, untagged arrays, untagged maps, tagged objects, untagged simple values (including True and False) and untagged floating point values sorts before the other object.
This method is consistent with the Equals method.
- Specified by:
compareToin interfaceComparable<CBORObject>- Parameters:
other- A value to compare with.- Returns:
- A negative number, if this value is less than the other object; or 0, if both values are equal; or a positive number, if this value is less than the other object or if the other object is null. This implementation returns a positive number if.
-
CompareToIgnoreTags
Compares this object and another CBOR object, ignoring the tags they have, if any. See the compareTo method for more information on the comparison function.- Parameters:
other- A value to compare with.- Returns:
- Less than 0, if this value is less than the other object; or 0, if both values are equal; or greater than 0, if this value is less than the other object or if the other object is null.
-
ContainsKey
Determines whether a value of the given key exists in this object.- Parameters:
objKey- The parameterobjKeyis an arbitrary object.- Returns:
trueif the given key is found, orfalseif the given key is not found or this object is not a map.
-
ContainsKey
Determines whether a value of the given key exists in this object.- Parameters:
key- An object that serves as the key. If this isnull, checks forCBORObject.Null.- Returns:
trueif the given key is found, orfalseif the given key is not found or this object is not a map.
-
ContainsKey
Determines whether a value of the given key exists in this object.- Parameters:
key- A text string that serves as the key. If this isnull, checks forCBORObject.Null.- Returns:
trueif the given key (as a CBOR object) is found, orfalseif the given key is not found or this object is not a map.
-
EncodeToBytes
public byte[] EncodeToBytes()Writes the binary representation of this CBOR object and returns a byte array of that representation. If the CBOR object contains CBOR maps, or is a CBOR map itself, the order in which the keys to the map are written out to the byte array is undefined unless the map was created using the NewOrderedMap method. The example code given incom.upokecenter.cbor.CBORObject.WriteTo(System.IO.InputStream)can be used to write out certain keys of a CBOR map in a given order. For the CTAP2 (FIDO Client-to-Authenticator Protocol 2) canonical ordering, which is useful for implementing Web Authentication, callEncodeToBytes(new CBOREncodeOptions("ctap2canonical=true"))rather than this method.- Returns:
- A byte array in CBOR format.
-
EncodeToBytes
Writes the binary representation of this CBOR object and returns a byte array of that representation, using the specified options for encoding the object to CBOR format. For the CTAP2 (FIDO Client-to-Authenticator Protocol 2) canonical ordering, which is useful for implementing Web Authentication, call this method as follows:EncodeToBytes(new CBOREncodeOptions("ctap2canonical=true")).- Parameters:
options- Options for encoding the data to CBOR.- Returns:
- A byte array in CBOR format.
- Throws:
NullPointerException- The parameteroptionsis null.
-
AtJSONPointer
Gets the CBOR object referred to by a JSON Pointer according to RFC6901. For more information, see the overload taking a default value parameter.- Parameters:
pointer- A JSON pointer according to RFC 6901.- Returns:
- An object within this CBOR object. Returns this object if pointer is the empty string (even if this object has a CBOR type other than array or map).
- Throws:
CBORException- Thrown if the pointer is null, or if the pointer is invalid, or if there is no object at the given pointer, or the special key "-" appears in the pointer in the context of an array (not a map), or if the pointer is non-empty and this object has a CBOR type other than array or map.
-
AtJSONPointer
Gets the CBOR object referred to by a JSON Pointer according to RFC6901, or a default value if the operation fails. The syntax for a JSON Pointer is:
'/' KEY '/' KEY.get(...)
where KEY represents a key into the JSON object or its sub-objects in the hierarchy. For example,/foo/2/bar
means the same asobj.get('foo')[2]['bar']in JavaScript. If "~" and/or "/" occurs in a key, it must be escaped with "~0" or "~1", respectively, in a JSON pointer. JSON pointers also support the special key "-" (as in "/foo/-") to indicate the end of an array, but this method treats this key as an error since it refers to a nonexistent item. Indices to arrays (such as 2 in the example) must contain only basic digits 0 to 9 and no leading zeros. (Note that RFC 6901 was published before JSON was extended to support top-level values other than arrays and key-value dictionaries.).- Parameters:
pointer- A JSON pointer according to RFC 6901.defaultValue- The parameterdefaultValueis a Cbor.CBORObject object.- Returns:
- An object within the specified JSON object. Returns this object if
pointer is the empty string (even if this object has a CBOR type other than
array or map). Returns
defaultValueif the pointer is null, or if the pointer is invalid, or if there is no object at the given pointer, or the special key "-" appears in the pointer in the context of an array (not a map), or if the pointer is non-empty and this object has a CBOR type other than array or map.
-
ApplyJSONPatch
Returns a copy of this object after applying the operations in a JSON patch, in the form of a CBOR object. JSON patches are specified in RFC 6902 and their format is summarized in the remarks below.
Remarks: A JSON patch is an array with one or more maps. Each map has the following keys:
- "op" - Required. This key's value is the patch operation and must be "add", "remove", "move", "copy", "test", or "replace", in basic lower case letters and no other case combination.
- "value" - Required if the operation is "add", "replace", or "test" and specifies the item to add (insert), or that will replace the existing item, or to check an existing item for equality, respectively. (For "test", the operation fails if the existing item doesn't match the specified value.)
- "path" - Required for all operations. A JSON Pointer (RFC 6901) specifying the destination path in the CBOR object for the operation. For more information, see RFC 6901 or the documentation for AtJSONPointer(pointer, defaultValue).
- "from" - Required if the operation is "move" or "copy". A JSON Pointer (RFC 6901) specifying the path in the CBOR object where the source value is located.
- Parameters:
patch- A JSON patch in the form of a CBOR object; it has the form summarized in the remarks.- Returns:
- The result of the patch operation.
- Throws:
CBORException- The parameterpatchis null or the patch operation failed.
-
equals
Determines whether this object and another object are equal and have the same type. Not-a-number values can be considered equal by this method. -
equals
Compares the equality of two CBOR objects. Not-a-number values can be considered equal by this method.- Parameters:
other- The object to compare.- Returns:
trueif the objects are equal; otherwise,false. In this method, two objects are not equal if they don't have the same type or if one is null and the other isn't.
-
GetByteString
public byte[] GetByteString()Gets the backing byte array used in this CBOR object, if this object is a byte string, without copying the data to a new byte array. Any changes in the returned array's contents will be reflected in this CBOR object. Note, though, that the array's length can't be changed.- Returns:
- The byte array held by this CBOR object.
- Throws:
IllegalStateException- This object is not a byte string.
-
hashCode
public int hashCode()Calculates the hash code of this object. The hash code for a given instance of this class is not guaranteed to be the same across versions of this class, and no application or process IDs are used in the hash code calculation. -
GetAllTags
public com.upokecenter.numbers.EInteger[] GetAllTags()Gets a list of all tags, from outermost to innermost.- Returns:
- An array of tags, or the empty string if this object is untagged.
-
HasOneTag
public boolean HasOneTag()Returns whether this object has only one tag.- Returns:
trueif this object has only one tag; otherwise,false.
-
HasOneTag
public boolean HasOneTag(int tagValue) Returns whether this object has only one tag and that tag is the given number.- Parameters:
tagValue- The tag number.- Returns:
trueif this object has only one tag and that tag is the given number; otherwise,false.- Throws:
IllegalArgumentException- The parametertagValueis less than 0.
-
HasOneTag
public boolean HasOneTag(com.upokecenter.numbers.EInteger bigTagValue) Returns whether this object has only one tag and that tag is the given number, expressed as an arbitrary-precision integer.- Parameters:
bigTagValue- An arbitrary-precision integer.- Returns:
trueif this object has only one tag and that tag is the given number; otherwise,false.- Throws:
NullPointerException- The parameterbigTagValueis null.IllegalArgumentException- The parameterbigTagValueis less than 0.
-
getTagCount
public final int getTagCount()Gets the number of tags this object has.- Returns:
- The number of tags this object has.
-
HasMostInnerTag
public boolean HasMostInnerTag(int tagValue) Returns whether this object has an innermost tag and that tag is of the given number.- Parameters:
tagValue- The tag number.- Returns:
trueif this object has an innermost tag and that tag is of the given number; otherwise,false.- Throws:
IllegalArgumentException- The parametertagValueis less than 0.
-
HasMostInnerTag
public boolean HasMostInnerTag(com.upokecenter.numbers.EInteger bigTagValue) Returns whether this object has an innermost tag and that tag is of the given number, expressed as an arbitrary-precision number.- Parameters:
bigTagValue- The tag number.- Returns:
trueif this object has an innermost tag and that tag is of the given number; otherwise,false.- Throws:
NullPointerException- The parameterbigTagValueis null.IllegalArgumentException- The parameterbigTagValueis less than 0.
-
HasMostOuterTag
public boolean HasMostOuterTag(int tagValue) Returns whether this object has an outermost tag and that tag is of the given number.- Parameters:
tagValue- The tag number.- Returns:
trueif this object has an outermost tag and that tag is of the given number; otherwise,false.- Throws:
IllegalArgumentException- The parametertagValueis less than 0.
-
HasMostOuterTag
public boolean HasMostOuterTag(com.upokecenter.numbers.EInteger bigTagValue) Returns whether this object has an outermost tag and that tag is of the given number.- Parameters:
bigTagValue- The tag number.- Returns:
trueif this object has an outermost tag and that tag is of the given number; otherwise,false.- Throws:
NullPointerException- The parameterbigTagValueis null.IllegalArgumentException- The parameterbigTagValueis less than 0.
-
HasTag
public boolean HasTag(int tagValue) Returns whether this object has a tag of the given number.- Parameters:
tagValue- The tag value to search for.- Returns:
trueif this object has a tag of the given number; otherwise,false.- Throws:
IllegalArgumentException- The parametertagValueis less than 0.NullPointerException- The parametertagValueis null.
-
HasTag
public boolean HasTag(com.upokecenter.numbers.EInteger bigTagValue) Returns whether this object has a tag of the given number.- Parameters:
bigTagValue- The tag value to search for.- Returns:
trueif this object has a tag of the given number; otherwise,false.- Throws:
NullPointerException- The parameterbigTagValueis null.IllegalArgumentException- The parameterbigTagValueis less than 0.
-
Insert
Inserts an object at the specified position in this CBOR array.- Parameters:
index- Index starting at 0 to insert at.valueOb- An object representing the value, which will be converted to a CBORObject. Can be null, in which case this value is converted to CBORObject.Null.- Returns:
- This instance.
- Throws:
IllegalStateException- This object is not an array.IllegalArgumentException- The parametervalueObhas an unsupported type; orindexis not a valid index into this array.
-
IsInfinity
Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsInfinity()).Gets a value indicating whether this CBOR object represents infinity.- Returns:
trueif this CBOR object represents infinity; otherwise,false.
-
IsNaN
Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsNaN()).Gets a value indicating whether this CBOR object represents a not-a-number value (as opposed to whether this object does not express a number).- Returns:
trueif this CBOR object represents a not-a-number value (as opposed to whether this object does not represent a number as defined by the IsNumber property orisNumber()method in Java); otherwise,false.
-
IsNegativeInfinity
Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsNegativeInfinity()).Gets a value indicating whether this CBOR object represents negative infinity.- Returns:
trueif this CBOR object represents negative infinity; otherwise,false.
-
IsPositiveInfinity
Deprecated.Instead, use the following: (cbor.isNumber() && cbor.AsNumber().IsPositiveInfinity()).Gets a value indicating whether this CBOR object represents positive infinity.- Returns:
trueif this CBOR object represents positive infinity; otherwise,false.
-
Negate
Deprecated.Instead, convert this object to a number (with .AsNumber()), and use that number's.Negate() method.Gets this object's value with the sign reversed.- Returns:
- The reversed-sign form of this number.
- Throws:
IllegalStateException- This object does not represent a number (for this purpose, infinities and not-a-number or NaN values, but not CBORObject.Null, are considered numbers).
-
Clear
public void Clear()Removes all items from this CBOR array or all keys and values from this CBOR map.- Throws:
IllegalStateException- This object is not a CBOR array or CBOR map.
-
Remove
If this object is an array, removes the first instance of the specified item (once converted to a CBOR object) from the array. If this object is a map, removes the item with the given key (once converted to a CBOR object) from the map.- Parameters:
obj- The item or key (once converted to a CBOR object) to remove.- Returns:
trueif the item was removed; otherwise,false.- Throws:
NullPointerException- The parameterobjis null (as opposed to CBORObject.Null).IllegalStateException- The object is not an array or map.
-
RemoveAt
public boolean RemoveAt(int index) Removes the item at the given index of this CBOR array.- Parameters:
index- The index, starting at 0, of the item to remove.- Returns:
- Returns "true" if the object was removed. Returns "false" if the given index is less than 0, or is at least as high as the number of items in the array.
- Throws:
IllegalStateException- This object is not a CBOR array.
-
Remove
If this object is an array, removes the first instance of the specified item from the array. If this object is a map, removes the item with the given key from the map.- Parameters:
obj- The item or key to remove.- Returns:
trueif the item was removed; otherwise,false.- Throws:
NullPointerException- The parameterobjis null (as opposed to CBORObject.Null).IllegalStateException- The object is not an array or map.
-
Set
Maps an object to a key in this CBOR map, or adds the value if the key doesn't exist. If this is a CBOR array, instead sets the value at the given index to the given value.- Parameters:
key- If this instance is a CBOR map, this parameter is an object representing the key, which will be converted to a CBORObject; in this case, this parameter can be null, in which case this value is converted to CBORObject.Null. If this instance is a CBOR array, this parameter must be a 32-bit signed integer(int) identifying the index (starting from 0) of the item to set in the array.valueOb- An object representing the value, which will be converted to a CBORObject. Can be null, in which case this value is converted to CBORObject.Null.- Returns:
- This instance.
- Throws:
IllegalStateException- This object is not a map or an array.IllegalArgumentException- The parameterkeyorvalueObhas an unsupported type, or this instance is a CBOR array andkeyis less than 0, is the size of this array or greater, or is not a 32-bit signed integer (int).
-
ToJSONString
Converts this object to a text string in JavaScript object Notation (JSON) format. See the overload to ToJSONString taking a JSONOptions argument for further information.
If the CBOR object contains CBOR maps, or is a CBOR map itself, the order in which the keys to the map are written out to the JSON string is undefined unless the map was created using the NewOrderedMap method. Map keys other than untagged text strings are converted to JSON strings before writing them out (for example,
22("Test")is converted to"Test"andtrueis converted to"true"). After such conversion, if two or more keys for the same map are identical, this method throws a CBORException. The example code given in PeterO.Cbor.CBORObject.ToJSONString(PeterO.Cbor.JSONOptions) can be used to write out certain keys of a CBOR map in a given order to a JSON string, or to write out a CBOR object as part of a JSON text sequence.Warning: In general, if this CBOR object contains integer map keys or uses other features not supported in JSON, and the application converts this CBOR object to JSON and back to CBOR, the application should not expect the new CBOR object to be exactly the same as the original. This is because the conversion in many cases may have to convert unsupported features in JSON to supported features which correspond to a different feature in CBOR (such as converting integer map keys, which are supported in CBOR but not JSON, to text strings, which are supported in both).
- Returns:
- A text string containing the converted object in JSON format.
-
ToJSONString
Converts this object to a text string in JavaScript object Notation (JSON) format, using the specified options to control the encoding process. This function works not only with arrays and maps, but also integers, strings, byte arrays, and other JSON data types. Notes:
- If this object contains maps with non-string keys, the keys are converted to JSON strings before writing the map as a JSON string.
- If this object represents a number (the IsNumber property, or isNumber() method in Java, returns true), then it is written out as a number.
- If the CBOR
object contains CBOR maps, or is a CBOR map itself, the order in which the
keys to the map are written out to the JSON string is undefined unless the
map was created using the NewOrderedMap method. Map keys other than untagged
text strings are converted to JSON strings before writing them out (for
example,
22("Test")is converted to"Test"andtrueis converted to"true"). After such conversion, if two or more keys for the same map are identical, this method throws a CBORException. - If a number in the form of an arbitrary-precision binary floating-point number has a very high binary exponent, it will be converted to a double before being converted to a JSON string. (The resulting double could overflow to infinity, in which case the arbitrary-precision binary floating-point number is converted to null.)
- The string will not begin with a byte-order mark (U+FEFF); RFC 8259 (the JSON specification) forbids placing a byte-order mark at the beginning of a JSON string.
- Byte strings are converted to Base64 URL
without whitespace or padding by default (see section 3.4.5.3 of RFC 8949).
A byte string will instead be converted to traditional base64 without
whitespace and with padding if it has tag 22, or base16 for tag 23. (To
create a CBOR object with a given tag, call the
CBORObject.FromObjectAndTagmethod and pass the CBOR object and the desired tag number to that method.) - Rational numbers will be converted to their exact form, if possible, otherwise to a high-precision approximation. (The resulting approximation could overflow to infinity, in which case the rational number is converted to null.)
- Simple values other than true and false will be converted to null. (This doesn't include floating-point numbers.)
- Infinity and not-a-number will be converted to null.
Warning: In general, if this CBOR object contains integer map keys or uses other features not supported in JSON, and the application converts this CBOR object to JSON and back to CBOR, the application should not expect the new CBOR object to be exactly the same as the original. This is because the conversion in many cases may have to convert unsupported features in JSON to supported features which correspond to a different feature in CBOR (such as converting integer map keys, which are supported in CBOR but not JSON, to text strings, which are supported in both).
The example code given below (originally written in C# for the.NET version) can be used to write out certain keys of a CBOR map in a given order to a JSON string.
/* Generates a JSON string of 'mapObj' whose keys are in the order given in 'keys' . Only keys found in 'keys' will be written if they exist in 'mapObj'. */ private static string KeysToJSONMap(CBORObject mapObj, List<CBORObject> keys) { if (mapObj == null) { throw new NullPointerException)"mapObj");} if (keys == null) { throw new NullPointerException)"keys");} if (obj.getType() != CBORType.Map) { throw new IllegalArgumentException("'obj' is not a map."); } StringBuilder builder = new StringBuilder(); boolean first = true; builder.append("{"); for (CBORObject key in keys) { if (mapObj.ContainsKey(key)) { if (!first) {builder.append(", ");} var keyString=(key.getCBORType() == CBORType.string) ? key.AsString() : key.ToJSONString(); builder.append(CBORObject.FromObject(keyString) .ToJSONString()) .append(":").append(mapObj.get(key).ToJSONString()); first=false; } } return builder.append("}").toString(); }.- Parameters:
options- Specifies options to control writing the CBOR object to JSON.- Returns:
- A text string containing the converted object in JSON format.
- Throws:
NullPointerException- The parameteroptionsis null.
-
toString
Returns this CBOR object in a text form intended to be read by humans. The value returned by this method is not intended to be parsed by computer programs, and the exact text of the value may change at any time between versions of this library.
The returned string is not necessarily in JavaScript object Notation (JSON); to convert CBOR objects to JSON strings, use the PeterO.Cbor.CBORObject.ToJSONString(PeterO.Cbor.JSONOptions) method instead.
-
Untag
Gets an object with the same value as this one but without the tags it has, if any. If this object is an array, map, or byte string, the data will not be copied to the returned object, so changes to the returned object will be reflected in this one.- Returns:
- A CBOR object.
-
UntagOne
Gets an object with the same value as this one but without this object's outermost tag, if any. If this object is an array, map, or byte string, the data will not be copied to the returned object, so changes to the returned object will be reflected in this one.- Returns:
- A CBOR object.
-
WriteJSONTo
Converts this object to a text string in JavaScript object Notation (JSON) format, as in the ToJSONString method, and writes that string to a data stream in UTF-8. If the CBOR object contains CBOR maps, or is a CBOR map, the order in which the keys to the map are written out to the JSON string is undefined unless the map was created using the NewOrderedMap method. The example code given in PeterO.Cbor.CBORObject.ToJSONString(PeterO.Cbor.JSONOptions) can be used to write out certain keys of a CBOR map in a given order to a JSON string.
The following example (originally written in C# for the.NET version) writes out a CBOR object as part of a JSON text sequence (RFC 7464).
stream.write(0x1e); /* RS */ cborObject.WriteJSONTo(stream); /* JSON */ stream.write(0x0a); /* LF */
The following example (originally written in C# for the.NET version) shows how to use the
LimitedMemoryStreamclass (implemented in LimitedMemoryStream.cs in the peteroupc/CBOR open-source repository) to limit the size of supported JSON serializations of CBOR objects./* maximum supported JSON size in bytes*/ int maxSize = 20000; { LimitedMemoryStream ms = null; try { ms = new LimitedMemoryStream(maxSize); cborObject.WriteJSONTo(ms); Array bytes = ms.toByteArray(); } finally { try { if (ms != null) { ms.close(); } } catch (java.io.IOException ex) {} } }The following example (written in Java for the Java version) shows how to use a subclassed
OutputStreamtogether with aByteArrayOutputStreamto limit the size of supported JSON serializations of CBOR objects./* maximum supported JSON size in bytes*/ final int maxSize = 20000; ByteArrayOutputStream ba = new ByteArrayOutputStream(); /* throws UnsupportedOperationException if too big*/ cborObject.WriteJSONTo(new FilterOutputStream(ba) { private int size = 0; public void write(byte[] b, int off, int len) { if (len>(maxSize-size)) { throw new UnsupportedOperationException(); } size+=len; out.write(b, off, len); } public void write(byte b) { if (size >= maxSize) { throw new UnsupportedOperationException(); } size++; out.write(b); } }); byte[] bytes = ba.toByteArray();The following example (originally written in C# for the.NET version) shows how to use a.NET MemoryStream to limit the size of supported JSON serializations of CBOR objects. The disadvantage is that the extra memory needed to do so can be wasteful, especially if the average serialized object is much smaller than the maximum size given (for example, if the maximum size is 20000 bytes, but the average serialized object has a size of 50 bytes).
byte[] backing = new byte[20000]; /* maximum supported JSON size in bytes*/ byte[] bytes1, bytes2; { java.io.ByteArrayOutputStream ms = null; try { ms = new java.io.ByteArrayOutputStream(backing); /* throws UnsupportedOperationException if too big*/ cborObject.WriteJSONTo(ms); bytes1 = new byte[ms.size()]; /* Copy serialized data if successful*/ System.ArrayCopy(backing, 0, bytes1, 0, (int)ms.size()); /* Reset memory stream*/ ms.size() = 0; cborObject2.WriteJSONTo(ms); bytes2 = new byte[ms.size()]; /* Copy serialized data if successful*/ System.ArrayCopy(backing, 0, bytes2, 0, (int)ms.size()); } finally { try { if (ms != null) { ms.close(); } } catch (java.io.IOException ex) {} } }- Parameters:
outputStream- A writable data stream.- Throws:
IOException- An I/O error occurred.NullPointerException- The parameteroutputStreamis null.
-
WriteJSONTo
Converts this object to a text string in JavaScript object Notation (JSON) format, as in the ToJSONString method, and writes that string to a data stream in UTF-8, using the given JSON options to control the encoding process. If the CBOR object contains CBOR maps, or is a CBOR map, the order in which the keys to the map are written out to the JSON string is undefined unless the map was created using the NewOrderedMap method. The example code given in PeterO.Cbor.CBORObject.ToJSONString(PeterO.Cbor.JSONOptions) can be used to write out certain keys of a CBOR map in a given order to a JSON string.
- Parameters:
outputStream- A writable data stream.options- An object containing the options to control writing the CBOR object to JSON.- Throws:
IOException- An I/O error occurred.NullPointerException- The parameteroutputStreamis null.
-
FromFloatingPointBits
Generates a CBOR object from a floating-point number represented by its bits.- Parameters:
floatingBits- The bits of a floating-point number number to write.byteCount- The number of bytes of the stored floating-point number; this also specifies the format of the "floatingBits" parameter. This value can be 2 if "floatingBits"'s lowest (least significant) 16 bits identify the floating-point number in IEEE 754r binary16 format; or 4 if "floatingBits"'s lowest (least significant) 32 bits identify the floating-point number in IEEE 754r binary32 format; or 8 if "floatingBits" identifies the floating point number in IEEE 754r binary64 format. Any other values for this parameter are invalid.- Returns:
- A CBOR object storing the given floating-point number.
- Throws:
IllegalArgumentException- The parameterbyteCountis other than 2, 4, or 8.
-
WriteFloatingPointBits
public static int WriteFloatingPointBits(OutputStream outputStream, long floatingBits, int byteCount) throws IOException Writes the bits of a floating-point number in CBOR format to a data stream.- Parameters:
outputStream- A writable data stream.floatingBits- The bits of a floating-point number number to write.byteCount- The number of bytes of the stored floating-point number; this also specifies the format of the "floatingBits" parameter. This value can be 2 if "floatingBits"'s lowest (least significant) 16 bits identify the floating-point number in IEEE 754r binary16 format; or 4 if "floatingBits"'s lowest (least significant) 32 bits identify the floating-point number in IEEE 754r binary32 format; or 8 if "floatingBits" identifies the floating point number in IEEE 754r binary64 format. Any other values for this parameter are invalid. This method will write one plus this many bytes to the data stream.- Returns:
- The number of 8-bit bytes ordered to be written to the data stream.
- Throws:
IllegalArgumentException- The parameterbyteCountis other than 2, 4, or 8.NullPointerException- The parameteroutputStreamis null.IOException
-
WriteFloatingPointBits
public static int WriteFloatingPointBits(OutputStream outputStream, long floatingBits, int byteCount, boolean shortestForm) throws IOException Writes the bits of a floating-point number in CBOR format to a data stream.- Parameters:
outputStream- A writable data stream.floatingBits- The bits of a floating-point number number to write.byteCount- The number of bytes of the stored floating-point number; this also specifies the format of the "floatingBits" parameter. This value can be 2 if "floatingBits"'s lowest (least significant) 16 bits identify the floating-point number in IEEE 754r binary16 format; or 4 if "floatingBits"'s lowest (least significant) 32 bits identify the floating-point number in IEEE 754r binary32 format; or 8 if "floatingBits" identifies the floating point number in IEEE 754r binary64 format. Any other values for this parameter are invalid.shortestForm- If true, writes the shortest form of the floating-point number that preserves its value. If false, this method will write the number in the form given by 'floatingBits' by writing one plus the number of bytes given by 'byteCount' to the data stream.- Returns:
- The number of 8-bit bytes ordered to be written to the data stream.
- Throws:
IllegalArgumentException- The parameterbyteCountis other than 2, 4, or 8.NullPointerException- The parameteroutputStreamis null.IOException
-
WriteFloatingPointValue
public static int WriteFloatingPointValue(OutputStream outputStream, double doubleVal, int byteCount) throws IOException Writes a 64-bit binary floating-point number in CBOR format to a data stream, either in its 64-bit form, or its rounded 32-bit or 16-bit equivalent.- Parameters:
outputStream- A writable data stream.doubleVal- The double-precision floating-point number to write.byteCount- The number of 8-bit bytes of the stored number. This value can be 2 to store the number in IEEE 754r binary16, rounded to nearest, ties to even; or 4 to store the number in IEEE 754r binary32, rounded to nearest, ties to even; or 8 to store the number in IEEE 754r binary64. Any other values for this parameter are invalid.- Returns:
- The number of 8-bit bytes ordered to be written to the data stream.
- Throws:
IllegalArgumentException- The parameterbyteCountis other than 2, 4, or 8.NullPointerException- The parameteroutputStreamis null.IOException
-
WriteFloatingPointValue
public static int WriteFloatingPointValue(OutputStream outputStream, float singleVal, int byteCount) throws IOException Writes a 32-bit binary floating-point number in CBOR format to a data stream, either in its 64- or 32-bit form, or its rounded 16-bit equivalent.- Parameters:
outputStream- A writable data stream.singleVal- The single-precision floating-point number to write.byteCount- The number of 8-bit bytes of the stored number. This value can be 2 to store the number in IEEE 754r binary16, rounded to nearest, ties to even; or 4 to store the number in IEEE 754r binary32; or 8 to store the number in IEEE 754r binary64. Any other values for this parameter are invalid.- Returns:
- The number of 8-bit bytes ordered to be written to the data stream.
- Throws:
IllegalArgumentException- The parameterbyteCountis other than 2, 4, or 8.NullPointerException- The parameteroutputStreamis null.IOException
-
WriteValue
public static int WriteValue(OutputStream outputStream, int majorType, long value) throws IOException Writes a CBOR major type number and an integer 0 or greater associated with it to a data stream, where that integer is passed to this method as a 64-bit signed integer. This is a low-level method that is useful for implementing custom CBOR encoding methodologies. This method encodes the given major type and value in the shortest form allowed for the major type.
There are other useful things to note when encoding CBOR that are not covered by this WriteValue method. To mark the start of an indefinite-length array, write the 8-bit byte 0x9f to the output stream. To mark the start of an indefinite-length map, write the 8-bit byte 0xbf to the output stream. To mark the end of an indefinite-length array or map, write the 8-bit byte 0xff to the output stream. For examples, see the WriteValue(InputStream, int, int) overload.
- Parameters:
outputStream- A writable data stream.majorType- The CBOR major type to write. This is a number from 0 through 7 as follows. 0: integer 0 or greater; 1: negative integer; 2: byte string; 3: UTF-8 text string; 4: array; 5: map; 6: tag; 7: simple value. See RFC 8949 for details on these major types.value- An integer 0 or greater associated with the major type, as follows. 0: integer 0 or greater; 1: the negative integer's absolute value is 1 plus this number; 2: length in bytes of the byte string; 3: length in bytes of the UTF-8 text string; 4: number of items in the array; 5: number of key-value pairs in the map; 6: tag number; 7: simple value number, which must be in the interval [0, 23] or.charAt(32, 255).- Returns:
- The number of bytes ordered to be written to the data stream.
- Throws:
IllegalArgumentException- Value is from 24 to 31 and major type is 7.NullPointerException- The parameteroutputStreamis null.IOException
-
WriteValue
public static int WriteValue(OutputStream outputStream, int majorType, int value) throws IOException Writes a CBOR major type number and an integer 0 or greater associated with it to a data stream, where that integer is passed to this method as a 32-bit signed integer. This is a low-level method that is useful for implementing custom CBOR encoding methodologies. This method encodes the given major type and value in the shortest form allowed for the major type.
There are other useful things to note when encoding CBOR that are not covered by this WriteValue method. To mark the start of an indefinite-length array, write the 8-bit byte 0x9f to the output stream. To mark the start of an indefinite-length map, write the 8-bit byte 0xbf to the output stream. To mark the end of an indefinite-length array or map, write the 8-bit byte 0xff to the output stream.
In the following example, an array of three objects is written as CBOR to a data stream.
/* array, length 3*/ CBORObject.WriteValue(stream, 4, 3); /* item 1 */ CBORObject.Write("hello world", stream); CBORObject.Write(25, stream); /* item 2*/ CBORObject.Write(false, stream); /* item 3*/In the following example, a map consisting of two key-value pairs is written as CBOR to a data stream.
CBORObject.WriteValue(stream, 5, 2); /* map, 2 pairs*/ CBORObject.Write("number", stream); /* key 1 */ CBORObject.Write(25, stream); /* value 1 */ CBORObject.Write("string", stream); /* key 2*/ CBORObject.Write("hello", stream); /* value 2*/In the following example (originally written in C# for the.NET Framework version), a text string is written as CBOR to a data stream.
string str = "hello world"; byte[] bytes = com.upokecenter.util.DataUtilities.GetUtf8Bytes(str, true); CBORObject.WriteValue(stream, 4, bytes.length); stream.write(bytes, 0, * bytes.length);
.- Parameters:
outputStream- A writable data stream.majorType- The CBOR major type to write. This is a number from 0 through 7 as follows. 0: integer 0 or greater; 1: negative integer; 2: byte string; 3: UTF-8 text string; 4: array; 5: map; 6: tag; 7: simple value. See RFC 8949 for details on these major types.value- An integer 0 or greater associated with the major type, as follows. 0: integer 0 or greater; 1: the negative integer's absolute value is 1 plus this number; 2: length in bytes of the byte string; 3: length in bytes of the UTF-8 text string; 4: number of items in the array; 5: number of key-value pairs in the map; 6: tag number; 7: simple value number, which must be in the interval [0, 23] or.charAt(32, 255).- Returns:
- The number of bytes ordered to be written to the data stream.
- Throws:
IllegalArgumentException- Value is from 24 to 31 and major type is 7.NullPointerException- The parameteroutputStreamis null.IOException
-
WriteValue
public static int WriteValue(OutputStream outputStream, int majorType, com.upokecenter.numbers.EInteger bigintValue) throws IOException Writes a CBOR major type number and an integer 0 or greater associated with it to a data stream, where that integer is passed to this method as an arbitrary-precision integer. This is a low-level method that is useful for implementing custom CBOR encoding methodologies. This method encodes the given major type and value in the shortest form allowed for the major type.
There are other useful things to note when encoding CBOR that are not covered by this WriteValue method. To mark the start of an indefinite-length array, write the 8-bit byte 0x9f to the output stream. To mark the start of an indefinite-length map, write the 8-bit byte 0xbf to the output stream. To mark the end of an indefinite-length array or map, write the 8-bit byte 0xff to the output stream.
- Parameters:
outputStream- A writable data stream.majorType- The CBOR major type to write. This is a number from 0 through 7 as follows. 0: integer 0 or greater; 1: negative integer; 2: byte string; 3: UTF-8 text string; 4: array; 5: map; 6: tag; 7: simple value. See RFC 8949 for details on these major types.bigintValue- An integer 0 or greater associated with the major type, as follows. 0: integer 0 or greater; 1: the negative integer's absolute value is 1 plus this number; 2: length in bytes of the byte string; 3: length in bytes of the UTF-8 text string; 4: number of items in the array; 5: number of key-value pairs in the map; 6: tag number; 7: simple value number, which must be in the interval [0, 23] or.charAt(32, 255). For major types 0 to 6, this number may not be greater than 2^64 - 1.- Returns:
- The number of bytes ordered to be written to the data stream.
- Throws:
IllegalArgumentException- The parametermajorTypeis 7 and value is greater than 255.NullPointerException- The parameteroutputStreamorbigintValueis null.IOException
-
WriteTo
Writes this CBOR object to a data stream. If the CBOR object contains CBOR maps, or is a CBOR map, the order in which the keys to the map are written out to the data stream is undefined unless the map was created using the NewOrderedMap method. See the examples (originally written in C# for the.NET version) for ways to write out certain keys of a CBOR map in a given order. In the case of CBOR objects of type FloatingPoint, the number is written using the shortest floating-point encoding possible; this is a change from previous versions.
The following example shows a method that writes each key of 'mapObj' to 'outputStream', in the order given in 'keys', where 'mapObj' is written out in the form of a CBOR definite-length map . Only keys found in 'keys' will be written if they exist in 'mapObj'.
private static void WriteKeysToMap(CBORObject mapObj, List<CBORObject> keys, OutputStream outputStream) { if (mapObj == null) { throw new NullPointerException("mapObj");} if (keys == null) {throw new NullPointerException("keys");} if (outputStream == null) {throw new NullPointerException("outputStream");} if (obj.getType()!=CBORType.Map) { throw new IllegalArgumentException("'obj' is not a map."); } int keyCount = 0; for (CBORObject key in keys) { if (mapObj.ContainsKey(key)) { keyCount++; } } CBORObject.WriteValue(outputStream, 5, keyCount); for (CBORObject key in keys) { if (mapObj.ContainsKey(key)) { key.WriteTo(outputStream); mapObj.get(key).WriteTo(outputStream); } } }The following example shows a method that writes each key of 'mapObj' to 'outputStream', in the order given in 'keys', where 'mapObj' is written out in the form of a CBOR indefinite-length map . Only keys found in 'keys' will be written if they exist in 'mapObj'.
private static void WriteKeysToIndefMap(CBORObject mapObj, List<CBORObject> keys, OutputStream outputStream) { if (mapObj == null) { throw new NullPointerException("mapObj");} if (keys == null) {throw new NullPointerException("keys");} if (outputStream == null) {throw new NullPointerException("outputStream");} if (obj.getType()!=CBORType.Map) { throw new IllegalArgumentException("'obj' is not a map."); } outputStream.write((byte)0xbf); for (CBORObject key in keys) { if (mapObj.ContainsKey(key)) { key.WriteTo(outputStream); mapObj.get(key).WriteTo(outputStream); } } outputStream.write((byte)0xff); }The following example shows a method that writes out a list of objects to 'outputStream' as an indefinite-length CBOR array .
private static void WriteToIndefArray(List<object> list, InputStream outputStream) { if (list == null) { throw new NullPointerException("list");} if (outputStream == null) {throw new NullPointerException("outputStream");} outputStream.write((byte)0x9f); for (object item in list) { new CBORObject(item).WriteTo(outputStream); } outputStream.write((byte)0xff); }The following example (originally written in C# for the.NET version) shows how to use the
LimitedMemoryStreamclass (implemented in LimitedMemoryStream.cs in the peteroupc/CBOR open-source repository) to limit the size of supported CBOR serializations./* maximum supported CBOR size in bytes*/ int maxSize = 20000; { LimitedMemoryStream ms = null; try { ms = new LimitedMemoryStream(maxSize); cborObject.WriteTo(ms); Array bytes = ms.toByteArray(); } finally { try { if (ms != null) { ms.close(); } } catch (java.io.IOException ex) {} } }The following example (written in Java for the Java version) shows how to use a subclassed
OutputStreamtogether with aByteArrayOutputStreamto limit the size of supported CBOR serializations./* maximum supported CBOR size in bytes*/ final int maxSize = 20000; ByteArrayOutputStream ba = new ByteArrayOutputStream(); /* throws UnsupportedOperationException if too big*/ cborObject.WriteTo(new FilterOutputStream(ba) { private int size = 0; public void write(byte[] b, int off, int len) { if (len>(maxSize-size)) { throw new UnsupportedOperationException(); } size+=len; out.write(b, off, len); } public void write(byte b) { if (size >= maxSize) { throw new UnsupportedOperationException(); } size++; out.write(b); } }); byte[] bytes = ba.toByteArray();The following example (originally written in C# for the.NET version) shows how to use a.NET MemoryStream to limit the size of supported CBOR serializations. The disadvantage is that the extra memory needed to do so can be wasteful, especially if the average serialized object is much smaller than the maximum size given (for example, if the maximum size is 20000 bytes, but the average serialized object has a size of 50 bytes).
byte[] backing = new byte[20000]; /* maximum supported CBOR size in bytes*/ byte[] bytes1, bytes2; using (MemoryStream ms = new java.io.ByteArrayInputStream(backing)) { /* throws UnsupportedOperationException if too big*/ cborObject.WriteTo(ms); bytes1 = new byte[ms.getPosition()]; /* Copy serialized data if successful*/ System.ArrayCopy(backing, 0, bytes1, 0, (int)ms.getPosition()); /* Reset memory stream*/ ms.setPosition(0); cborObject2.WriteTo(ms); bytes2 = new byte[ms.getPosition()]; /* Copy serialized data if successful*/ System.ArrayCopy(backing, 0, bytes2, 0, (int)ms.getPosition()); }- Parameters:
stream- A writable data stream.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.
-
WriteTo
Writes this CBOR object to a data stream, using the specified options for encoding the data to CBOR format. If the CBOR object contains CBOR maps, or is a CBOR map, the order in which the keys to the map are written out to the data stream is undefined unless the map was created using the NewOrderedMap method. The example code given incom.upokecenter.cbor.CBORObject.WriteTo(System.IO.InputStream)can be used to write out certain keys of a CBOR map in a given order. In the case of CBOR objects of type FloatingPoint, the number is written using the shortest floating-point encoding possible; this is a change from previous versions.- Parameters:
stream- A writable data stream.options- Options for encoding the data to CBOR.- Throws:
NullPointerException- The parameterstreamis null.IOException- An I/O error occurred.IllegalArgumentException- Unexpected data type".
-