java - 如何将数组放入 Hashmap 中以编码 JSON 对象

标签 java arrays json serialization hashmap

我尝试使用 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/

相关文章:

java - 初始化和 spring 集成 channel

java - Spring @transactional 不回滚

php - Mysql 查询似乎可以工作,但仍然出现错误?

c# - 如何跳过 Json.Net 中 IEnumerable 类型的默认 JavaScript 数组序列化?

json - 我可以在发布之前获取 http.NewRequest 的大小吗?

java - 画曲线,有什么建议

Java - 在大输入集中实现线程

arrays - 通过索引拒绝 Ruby 数组元素的惯用方法

javascript - 使用键动态构建最小值和最大值

javascript - 从 url 加载的多个 GeoJSon 标记未显示