我尝试使用 json-simple 1.1.1 发送 API 调用,并将字段和值保存为 HashMap。我应该发送这些参数:
{ api_key : string,
product_id : string,
name : string,
tax_rates : array }
这是一个 HashMap 示例:
HashMap<String,Object> arg = new HashMap<String, Object>();
arg.put("product_id","42");
arg.put("name", "EKOS");
arg.put("tax_rates", taxarray);
我也将taxarray保存为HashMap:
HashMap<String, Object> taxarray = new HashMap<String, Object>();
taxarray.put("name","EKOS");
taxarray.put("type", "type_value_fixed");
taxarray.put("value", "56");
但是当我执行 API 调用时,它会返回错误:参数“tax_rates”无效。所需的参数类型是数组。
我一直在尝试将taxarray HashMap 保存为JSONArray。你能帮我解决这个问题吗?
另一个问题:如何在一个“tax_rates”中保存 2 个或更多税率?这是一个例子:
HashMap<String,Object> arg = new HashMap<String, Object>();
arg.put("product_id","42");
arg.put("name", "EKOS");
arg.put("tax_rates", array [
taxarray1[],
taxarray2[]
]);
最佳答案
你应该有这样的东西 - 税收类别:
public class Tax {
String name;
String type;
Integer[] values;
public Tax(String name, String type, Integer[] values) {
this.name = name;
this.type = type;
this.values = values;
}
}
然后使用 Tax 类的对象数组代替 tax_rates : array
的 HashMap。
此代码使用谷歌 json:
Map<String, Object> arg = new HashMap<String, Object>();
arg.put("product_id", "42");
arg.put("name", "EKOS");
arg.put("tax_rates",
new Tax[] { new Tax("EKOS", "type_value_fixed", new Integer[] { 1, 2, 3 }),
new Tax("ABC", "type_value_fixed", new Integer[] { 4, 5 }),
new Tax("DEF", "type_value_fixed", new Integer[] { 6, 7}) });
Gson gson = new Gson();
System.out.println(gson.toJson(arg));
会给你这样的json:
{
"product_id": "42",
"name": "EKOS",
"tax_rates": [
{
"name": "EKOS",
"type": "type_value_fixed",
"values": [
1,
2,
3
]
},
{
"name": "ABC",
"type": "type_value_fixed",
"values": [
4,
5
]
},
{
"name": "DEF",
"type": "type_value_fixed",
"values": [
6,
7
]
}
]
}
关于java - 如何将数组放入 Hashmap 中以编码 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41370573/