gpt4 book ai didi

java - 使用 JSONObject 和 JSONArray 构建 JSON Web token

转载 作者:行者123 更新时间:2023-11-30 07:56:19 25 4
gpt4 key购买 nike

我正在使用 JSONObject 和 JSONArray 构建 JSON Web Token (JWT)。创建有效负载时,我需要匹配以下部分(包含数组的数组)

"Taxes":
[{
"VAT": [{ "TaxRate": "A", "Amount": 100 }, { "TaxRate": "B", "Amount": 300 }]
]}

我尝试使用以下代码来实现它

JSONArray taxes= new JSONArray();
JSONArray vat = new JSONArray();
vat.add(new JSONObject()
.put("TaxRate", "A")
.put("Amount", 100).toString());
vat.add(new JSONObject()
.put("TaxRate", "B")
.put("Amount", 300).toString());
taxes.add(new JSONObject()
.put("VAT", vat).toString());

问题

如果根本不调用 toString() 方法,则结果为 [{}]。如果在添加到 vat 数组时未调用它们,则结果为 ["{\"VAT\":\"[{},{}]\"}"]

打印到控制台时税费数组字符串的最终结果为["{\"VAT\":\"[\\\"{\\\\\\\"Amount\\\\\\\":100,\\\\\\\\"税率\\\\\\\":\\\\\\\"A\\\\\\\"}\\\",\\\"{\\\\\\\"金额\\\\\\\":300,\\\\\\\"税率\\\\\\\":\\\\\\\"B\\\\\\\"}\\\"]\"}"]

但是,vat 数组包含不带反斜杠的元素,例如。 {“金额”:100,“税率”:“A”}。税收数组有一个条目,看起来像 {"VAT":"[\"{\\\"Amount\\\":100,\\\"TaxRate\\\":\\\"A\\\"}\",\"{\\\"金额\\\":300,\\\"税率\\\":\\\"B\\\"}\"]"}

问题

构建我尝试创建的结构的正确方法是什么?

看起来 toString() 方法正在转义引号并添加斜杠。这种有效负载不能在请求中使用,因为服务器端应用程序无法解析它。

最佳答案

Nimbus Jose 使用 json-smart内部。因此,导入语句应如下所示:

import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;

创建json结构的代码:

JSONArray taxes= new JSONArray();
JSONArray vat = new JSONArray();
JSONObject a = new JSONObject();
a.put("TaxRate", "A");
a.put("Amount", 100);
vat.add(a);

JSONObject b = new JSONObject();
b.put("TaxRate", "B");
b.put("Amount", 300);
vat.add(b);

JSONObject vatObject = new JSONObject();
vatObject.put("VAT", vat);
taxes.add(vatObject);

JSONObject taxesObject = new JSONObject();
taxesObject.put("Taxes", taxes);

// generate string:
System.out.println(taxesObject.toJSONString());

// or create JWT:
new JWSObject(new JWSHeader(...), new Payload(taxesObject))

输出:

{"Taxes":[{"VAT":[{"Amount":100,"TaxRate":"A"},{"Amount":300,"TaxRate":"B"}]}]}

关于java - 使用 JSONObject 和 JSONArray 构建 JSON Web token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32626125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com