如何从两个 JSON 字符串创建 JSON 密钥集
Posted
技术标签:
【中文标题】如何从两个 JSON 字符串创建 JSON 密钥集【英文标题】:How to create a JSON Key Set from two JSON string 【发布时间】:2022-01-22 15:24:33 【问题描述】:我有两个对应于“sig”和“enc”的json字符串。
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"
我需要像这样将它们结合起来:
"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" ]
生成的 JSON 只不过是 JWKS,其中包括 sig 和 enc 公钥。我已经替换了这些参数的实际值。
【问题讨论】:
【参考方案1】:试试下面的代码:
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);
输出:
"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"]
使用的库:org.json
【讨论】:
我也尝试过,但是我的 jsonObject 将在输出中包含转义字符。关于如何解决它的任何想法? @yuhubug 你确定那些转义字符在 merging 这两个 JSON 对象之前不存在吗?如果他们不知道,您能否提供 正确 JSON 的示例,您期望什么以及您得到了什么? @yuhubug 您将在输入 JSON (a & b) 中有转义字符?【参考方案2】:请参考以下使用org.json
库实现的逻辑。
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);
【讨论】:
为什么是parser.parse(a).toString()
?
从源 JSON 文本字符串构造一个 JSONObject。这是 org.json.JSONObject 中定义的最常用的 JSONObject 构造函数,public JSONObject(String source) throws JSONException this(new JSONTokener(source));
@BipinKumarChaurasia 是的:只需将a
或b
传递给构造函数即可。
@BipinKumarChaurasia 我也尝试过,但我的 jsonObject 将在输出中包含转义字符。关于如何解决它的任何想法?
不,您不会有转义引号,因为在执行上述函数后已打印以下输出,"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"]
以上是关于如何从两个 JSON 字符串创建 JSON 密钥集的主要内容,如果未能解决你的问题,请参考以下文章