Class JSONObjectWriter
Also provides built-in support for encoding JSF (JSON Signature Format), JEF (JSON Encryption Format) and JWK objects.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceSupport interface for dynamic JSON generation. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final longIntegers outside of this range are not natively supported by I-JSON/JavaScript.static final String -
Constructor Summary
ConstructorsConstructorDescriptionCreates a fresh JSON object and associated writer.JSONObjectWriter(JSONObjectReader objectReader) For updating already read JSON objects. -
Method Summary
Modifier and TypeMethodDescriptioncopyElement(String newName, String sourceName, JSONObjectReader source) Copy arbitrary JSON data from aJSONObjectReaderstatic JSONObjectWritercreateCorePublicKey(PublicKey publicKey, AlgorithmPreferences algorithmPreferences) static JSONObjectWritercreateEncryptionObject(byte[] unencryptedData, ContentEncryptionAlgorithms contentEncryptionAlgorithm, JSONEncrypter encrypter) Create a JEF encrypted object.static JSONObjectWritercreateEncryptionObjects(byte[] unencryptedData, ContentEncryptionAlgorithms contentEncryptionAlgorithm, List<JSONEncrypter> encrypters) Create a JEF encrypted object for multiple recipients.byte[]serializeToBytes(JSONOutputFormats outputFormat) Serialize current object writer to a Javabyte[].serializeToString(JSONOutputFormats outputFormat) Serialize current object writer to a JavaString.Set (create) a JSON array.setArray(String name, JSONArrayWriter arrayWriter) Set a JSON array.setBigDecimal(String name, BigDecimal value) Set aBigDecimalproperty.setBigInteger(String name, BigInteger value) Set aBigIntegerproperty.Set abyte[]property.setBinaryArray(String name, List<byte[]> values) Set an array ofbyte[]property.setBoolean(String name, boolean value) Set abooleanproperty.setCertificatePath(X509Certificate[] certificatePath) Set a JSF certificate path property.setChainedSignature(String signatureLabel, JSONSigner signer) setChainedSignature(JSONSigner signer) Set a JSF chained-signature object.setDateTime(String name, GregorianCalendar dateTime, EnumSet<ISODateTime.DatePatterns> format) Set an ISO formatteddateTimeproperty.Set adoubleproperty.setDynamic(JSONObjectWriter.Dynamic jsonSetDynamic) Set JSON data using an external (dynamic) interface.Set anintproperty.Set alongproperty.Set alongproperty.setMoney(String name, BigDecimal value) Set aMoneyproperty.setMoney(String name, BigDecimal value, int decimals) Set aMoneyproperty.setMultiSignature(String signatureLabel, JSONSigner signer) setMultiSignature(JSONSigner signer) Set a JSF multi-signature object.Set a null property.Set (create) a JSON object.setObject(String name, JSONObjectReader objectReader) Set a JSON object.setObject(String name, JSONObjectWriter objectWriter) Set a JSON object.setPublicKey(PublicKey publicKey) setPublicKey(PublicKey publicKey, AlgorithmPreferences algorithmPreferences) setSignature(String signatureLabel, JSONSigner signer) setSignature(JSONSigner signer) Set a JSF"signature"object.Set a"string"property.setStringArray(String name, String[] values) Set aString[]property.voidsetupForRewrite(String name) Prepares the current object writer for a rewrite of a property.toString()Pretty print JSON of current object writer.
-
Field Details
-
MAX_INTEGER
public static final long MAX_INTEGERIntegers outside of this range are not natively supported by I-JSON/JavaScript.- See Also:
-
SIGNATURE_DEFAULT_LABEL_JSON
- See Also:
-
-
Constructor Details
-
JSONObjectWriter
For updating already read JSON objects.- Parameters:
objectReader- Existing object reader
-
JSONObjectWriter
public JSONObjectWriter()Creates a fresh JSON object and associated writer.
-
-
Method Details
-
setupForRewrite
Prepares the current object writer for a rewrite of a property.- Parameters:
name- Name of property to be rewritten
-
setString
Set a"string"property.Sample:
"statement": "Life is good!"- Parameters:
name- Propertyvalue- Value- Returns:
- Current instance of
JSONObjectWriter
-
setInt
Set anintproperty.Sample:
"headCount": 300- Parameters:
name- Propertyvalue- Value- Returns:
- Current instance of
JSONObjectWriter
-
setInt53
Set alongproperty.Sample:
Note that"quiteNegative": -800719925474099longdata is limited to 53 bits of precision (9007199254740992L), exceeding this limit throws an exception. If you need higher precision usesetLong(String, long).- Parameters:
name- Propertyvalue- Value- Returns:
- Current instance of
JSONObjectWriter - See Also:
-
setLong
Set alongproperty.Sample:
Note: This method puts the value within quotes to provide full 64-bit precision which does not have a native counterpart in JavaScript."quiteLong": "89007199254740991"- Parameters:
name- Propertyvalue- Value- Returns:
- Current instance of
JSONObjectWriter - See Also:
-
setDouble
Set adoubleproperty.Sample:
"Planck's Constant": 6.62607004e-34- Parameters:
name- Propertyvalue- Value- Returns:
- Current instance of
JSONObjectWriter
-
setBigInteger
Set aBigIntegerproperty.Note: this is a mapped type since there is no
BigIntegertype in JSON.Sample:
"aPrettyHugeNumber": "94673335822222222222222222222222222222222222222222222"- Parameters:
name- Propertyvalue- Value- Returns:
- Current instance of
JSONObjectWriter
-
setBigDecimal
Set aBigDecimalproperty.Note: this is a mapped type since there is no
BigDecimaltype in JSON.Sample:
"big": "56.67e+450"- Parameters:
name- Propertyvalue- Value- Returns:
- Current instance of
JSONObjectWriter
-
setMoney
Set aMoneyproperty.Note: this is a mapped type since there is no
Moneytype in JSON.Specification: https://www.w3.org/TR/payment-request/#dfn-valid-decimal-monetary-value.
Sample:"amount": "460.25"- Parameters:
name- Propertyvalue- Value- Returns:
- Current instance of
JSONObjectWriter - See Also:
-
setMoney
Set aMoneyproperty.Note: this is a mapped type since there is no
Moneytype in JSON.Specification: https://www.w3.org/TR/payment-request/#dfn-valid-decimal-monetary-value.
Sample:"amount": "460.25"- Parameters:
name- Propertyvalue- Valuedecimals- Number of fractional digits- Returns:
- Current instance of
JSONObjectWriter - See Also:
-
setBoolean
Set abooleanproperty.Sample:
"theEarthIsFlat": false- Parameters:
name- Propertyvalue- Value- Returns:
- Current instance of
JSONObjectWriter
-
setNULL
Set a null property.Sample:
"myKnowledgeOfTheLispProgrammingLanguage": null- Parameters:
name- Property- Returns:
- Current instance of
JSONObjectWriter - See Also:
-
setDateTime
public JSONObjectWriter setDateTime(String name, GregorianCalendar dateTime, EnumSet<ISODateTime.DatePatterns> format) Set an ISO formatteddateTimeproperty.Note: this is a mapped type since there is no
dateTimetype in JSON.Sample:
"received": "2016-11-12T09:22:36Z"- Parameters:
name- PropertydateTime- Date/time valueformat- Requited output format- Returns:
- Current instance of
JSONObjectWriter - See Also:
-
setBinary
Set abyte[]property.This method utilizes Base64Url encoding.
Sample:
"nonce": "lNxNvAUEE8t7DSQBft93LVSXxKCiVjhbWWfyg023FCk"- Parameters:
name- Propertyvalue- Array of bytes- Returns:
- Current instance of
JSONObjectWriter - See Also:
-
setObject
Set a JSON object.This method assigns a property name to an already existing object reader which is useful for wrapping JSON objects.
- Parameters:
name- PropertyobjectReader- Object reader- Returns:
- Current instance of
JSONObjectWriter
-
setObject
Set a JSON object.This method assigns a property name to an already created object writer which is useful for nested JSON objects.
- Parameters:
name- PropertyobjectWriter- Object writer- Returns:
- Current instance of
JSONObjectWriter
-
setObject
Set (create) a JSON object.This method creates an empty JSON object and links it to the current object through a property.
- Parameters:
name- Property- Returns:
- New instance of
JSONObjectWriter
-
setArray
Set (create) a JSON array.This method creates an empty JSON array and links it to the current object through a property.
- Parameters:
name- Property- Returns:
- New instance of
JSONArrayWriter
-
setArray
Set a JSON array.This method assigns a property name to an already created array writer which is useful for nested JSON objects.
- Parameters:
name- PropertyarrayWriter- Array writer- Returns:
- Current instance of
JSONObjectWriter
-
setBinaryArray
Set an array ofbyte[]property.This method puts each byte array (after Base64Url encoding) into a single JSON array.
Sample:
"blobs": ["lNxNvAUEE8t7DSQBft93LVSXxKCiVjhbWWfyg023FCk","LmTlQxXB3LgZrNLmhOfMaCnDizczC_RfQ6Kx8iNwfFA"]- Parameters:
name- Propertyvalues- List holding arrays of bytes- Returns:
- Current instance of
JSONObjectWriter - See Also:
-
setStringArray
Set aString[]property.This method puts each
Stringinto a single JSON array.Sample:
"usPresidents": ["Clinton","Bush","Obama","Trump"]- Parameters:
name- Propertyvalues- Array ofString- Returns:
- Current instance of
JSONObjectWriter
-
setDynamic
Set JSON data using an external (dynamic) interface.Sample using a construct suitable for chained writing:
setDynamic((wr) -> optionalString == null ? wr : wr.setString("opt", optionalString));- Parameters:
jsonSetDynamic- Interface (usually Lambda)- Returns:
- An instance of
JSONObjectWriter
-
copyElement
Copy arbitrary JSON data from aJSONObjectReader- Parameters:
newName- Property name in the current objectsourceName- Property name in the source objectsource- The JSON reader object- Returns:
- An instance of
JSONObjectWriter
-
setSignature
Set a JSF"signature"object.This method performs all the processing needed for adding a JSF signature to the current object.
- Parameters:
signer- The interface to the signing key and type- Returns:
- Current instance of
JSONObjectWriter
Sample Code:import java.io.IOException; import java.security.PrivateKey; import java.security.PublicKey; import org.webpki.crypto.AsymKeySignerInterface; import org.webpki.crypto.AsymSignatureAlgorithms; import org.webpki.crypto.SignatureWrapper; import org.webpki.json.JSONAsymKeySigner; import org.webpki.json.JSONAsymKeyVerifier; import org.webpki.json.JSONObjectReader; import org.webpki.json.JSONObjectWriter; import org.webpki.json.JSONParser; import org.webpki.json.JSONSignatureDecoder; . . . public void signAndVerifyJSF(PrivateKey privateKey, PublicKey publicKey) { // Create an empty JSON document JSONObjectWriter writer = new JSONObjectWriter(); // Fill it with some data writer.setString("myProperty", "Some data"); // Sign document writer.setSignature(new JSONAsymKeySigner(privateKey, publicKey, null)); // Serialize document String json = writer.toString(); // Print signed document on the console System.out.println(json);{ "myProperty": "Some data", "signature": { "algorithm": "ES256", "publicKey": { "kty": "EC", "crv": "P-256", "x": "PxlJQu9Q6dOvM4LKoZUh2XIe9-pdcLkvKfBfQk11Sb0", "y": "6IDquxrbdq5ABe4-HQ78_dhM6eEBUbvDtdqK31YfRP8" }, "value": "vHXWLfhmkl2qk3Eo5gwBFJy68RFMCJziviO8QkUAwarjNL4yrd5VGbYnYzoVLWj50up5A908_8eVDt_W0xJo7g" } }// Parse document JSONObjectReader reader = JSONParser.parse(json); // Get and verify signature JSONSignatureDecoder signature = reader.getSignature(new JSONCryptoHelper.Options()); signature.verify(new JSONAsymKeyVerifier(publicKey)); // Print document payload on the console System.out.println("Returned data: " + reader.getString("myProperty")); }
-
setSignature
-
setMultiSignature
Set a JSF multi-signature object.This method performs all the processing needed for adding multiple JSF signatures to the current object.
- Parameters:
signer- Signature interface- Returns:
- Current instance of
JSONObjectWriter
-
setMultiSignature
-
setChainedSignature
Set a JSF chained-signature object.This method performs all the processing needed for adding multiple JSF signatures to the current object.
- Parameters:
signer- Signature interface- Returns:
- Current instance of
JSONObjectWriter
-
setChainedSignature
-
createCorePublicKey
public static JSONObjectWriter createCorePublicKey(PublicKey publicKey, AlgorithmPreferences algorithmPreferences) Create a JSF (JWK) formatted public key.Typical use:
setObject("myPublicKey", JSONObjectWriter.setCorePublicKey(myPublicKey, AlgorithmPreferences.JOSE);Resulting JSON:"myPublicKey": { . depends on the actual public key type and value . }- Parameters:
publicKey- Public key valuealgorithmPreferences- JOSE or SKS algorithm notation- Returns:
- New instance of
JSONObjectWriter
-
setPublicKey
public JSONObjectWriter setPublicKey(PublicKey publicKey, AlgorithmPreferences algorithmPreferences) Set a JSF (JWK) formatted public key.Resulting JSON:
"publicKey": { . depends on the actual public key type and value . }- Parameters:
publicKey- Public key valuealgorithmPreferences- JOSE or SKS algorithm notation- Returns:
- Current instance of
JSONObjectWriter
-
setPublicKey
Set a JSF (JWK) formatted public key.This method is equivalent to
setPublicKey(PublicKey, AlgorithmPreferences)usingAlgorithmPreferences.JOSEas second argument.- Parameters:
publicKey- Public key value- Returns:
- Current instance of
JSONObjectWriter
-
setCertificatePath
Set a JSF certificate path property.Each path element (certificate) is base64url encoded and the path must be sorted where certificate[i] is signed by certificate[i + 1].
Resulting JSON:
"certificatePath": ["MIIETTCCAjWgAwIBAgIGAUoqo74...gfdd" {,...}]- Parameters:
certificatePath- Sorted certificate path array- Returns:
- Current instance of
JSONObjectWriter
-
createEncryptionObject
public static JSONObjectWriter createEncryptionObject(byte[] unencryptedData, ContentEncryptionAlgorithms contentEncryptionAlgorithm, JSONEncrypter encrypter) Create a JEF encrypted object.- Parameters:
unencryptedData- Data to be encryptedcontentEncryptionAlgorithm- Content encryption algorithmencrypter- Holds keys etc.- Returns:
- New instance of
JSONObjectWriter
-
createEncryptionObjects
public static JSONObjectWriter createEncryptionObjects(byte[] unencryptedData, ContentEncryptionAlgorithms contentEncryptionAlgorithm, List<JSONEncrypter> encrypters) Create a JEF encrypted object for multiple recipients.- Parameters:
unencryptedData- Data to be encryptedcontentEncryptionAlgorithm- Content encryption algorithmencrypters- Holds keys etc.- Returns:
- New instance of
JSONObjectWriter
-
serializeToString
Serialize current object writer to a JavaString.- Parameters:
outputFormat- Any JSONOutputFormats- Returns:
- JSON string data
-
serializeToBytes
Serialize current object writer to a Javabyte[].- Parameters:
outputFormat- Any JSONOutputFormats- Returns:
- JSON UTF-8 data
-
toString
Pretty print JSON of current object writer.
-