I have two json string coresponding to "sig" and "enc".
String a={ "kty": "someText", "e": "someText", "use": "sig", "kid": "someText", "alg": "someText", "n": "someText"}
String b= { "kty": "someText", "e": "someText", "use": "enc", "kid": "someText", "alg": "someText", "n": "someText" }
I need to combine them both like this:
{ "keys": [ { "kty": "someText", "e": "someText", "use": "sig", "kid": "someText", "alg": "someText", "n": "someText" }, { "kty": "someText", "e": "someText", "use": "enc", "kid": "someText", "alg": "someText", "n": "someText" } ] }
The resulting JSON is nothing but JWKS which includes both sig and enc public keys. I have replaced the actual values for these parameters.
CodePudding user response:
Try the below code :
public void test(){
String a="{ \"kty\": \"someText\", \"e\": \"someText\", \"use\": \"sig\", \"kid\": \"someText\", \"alg\": \"someText\", \"n\": \"someText\"}";
String b= "{ \"kty\": \"someText\", \"e\": \"someText\", \"use\": \"enc\", \"kid\": \"someText\", \"alg\": \"someText\", \"n\": \"someText\" }";
JSONObject jsonObject = new JSONObject(a);
JSONObject jsonObject1 = new JSONObject(b);
JSONArray objects1 = new JSONArray();
objects1.put(jsonObject);
objects1.put(jsonObject1);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("keys",objects1);
System.out.println(jsonObject2);
}
Output:
{"keys":[{"kty":"someText","e":"someText","use":"sig","kid":"someText","alg":"someText","n":"someText"},{"kty":"someText","e":"someText","use":"enc","kid":"someText","alg":"someText","n":"someText"}]}
Library used : org.json
CodePudding user response:
Please refer to the following logic implemented with org.json
library.
public void generateJSONObject() {
String a = "{ \"kty\": \"someText\", \"e\": \"someText\", \"use\": \"sig\", \"kid\": \"someText\", \"alg\": \"someText\", \"n\": \"someText\"}";
String b = "{ \"kty\": \"someText\", \"e\": \"someText\", \"use\": \"enc\", \"kid\": \"someText\", \"alg\": \"someText\", \"n\": \"someText\" }";
JSONObject jsonObject1 = new JSONObject(a);
JSONObject jsonObject2 = new JSONObject(b);
JSONObject jsonObject = new JSONObject();
jsonObject.append("keys", jsonObject1);
jsonObject.append("keys", jsonObject2);
System.out.println(jsonObject);
}