I am building JSON Web Token (JWT) using JSONObject and JSONArray. When creating a payload I need to match the following part (array that contains an array)
"Taxes":
[{
"VAT": [{ "TaxRate": "A", "Amount": 100 }, { "TaxRate": "B", "Amount": 300 }]
]}
I've tried to implement it with the following code
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());
Problems
If toString() methods are not called at all the result is [{}]. If they are not called when adding to vat array the result is ["{\"VAT\":\"[{},{}]\"}"].
The final result of the taxes array string when printed to the console is ["{\"VAT\":\"[\\\"{\\\\\\\"Amount\\\\\\\":100,\\\\\\\"TaxRate\\\\\\\":\\\\\\\"A\\\\\\\"}\\\",\\\"{\\\\\\\"Amount\\\\\\\":300,\\\\\\\"TaxRate\\\\\\\":\\\\\\\"B\\\\\\\"}\\\"]\"}"].
However, the vat array contains elements without backslashes, eg. {"Amount":100,"TaxRate":"A"}. The taxes array has one entry and it looks like {"VAT":"[\"{\\\"Amount\\\":100,\\\"TaxRate\\\":\\\"A\\\"}\",\"{\\\"Amount\\\":300,\\\"TaxRate\\\":\\\"B\\\"}\"]"}
Question
What is the correct way to build the structure I am trying to create?
It looks like the toString() method is escaping the quotes and adding the slashes. That kind of payload cannot be used in a request as the server side appliaction cannot parse it.