【问题标题】:Using HashMap to create complex JSON使用 HashMap 创建复杂的 JSON
【发布时间】:2021-10-27 17:46:57
【问题描述】:

我花了几天时间在谷歌上搜索这些不同的方式,但没有看到任何使用 HashMap 的示例 - 相反,它们都指的是 Jackson 或 GS​​ON。我无法使用这些,因为它们会导致 Jenkins 出现无法解决的问题(基本上所有东西都被超级锁定,工作场所不会“打开”替代方案)

我有一个 JSON 正文,我正尝试将它发送到创建记录 API。

对于简单的 JSON 正文,该过程非常简单:

所需的 JSON:

{
    "owner": {
        "firstName": "Steve",
        "lastName": "Guy",
        "Hair": "brown",
        "Eyes": "yes"
        "etc": "etc"
    },
    "somethingElse": "sure"
}

看起来像

Map<String,Object> jsonRequest = new HashMap<>();

Map<String,String> ownerMap = new HashMap<>();
HashMap<Object, String> OwnerMap = new HashMap<Object, String>;
    OwnerMap.put("firstName","Steve");
    OwnerMap.put("lastName","Guy");
    OwnerMap.put("Hair","brown");
    OwnerMap.put("Eyes","yes");
    OwnerMap.put("etc","etc");
jsonRequest.put("owner", OwnerMap);
jsonRequest.put("somethingElse", "sure");

很简单

如果 JSON 变得稍微复杂一些,我似乎无法弄清楚.. 我再次不能为此使用任何其他依赖项。

所以如果我有一个 JSON 正文需要发送:

{
  "customer": {
        "address": [
            {
              "address": "Blah"
             }
          ]
       },
   "anotherThing": "thing"
}

同样的模式不起作用。

Map<String,Object> jsonRequest = new HashMap<>();

Map<String,String> ownerMap = new HashMap<>();
HashMap<Object, String> addressMap = new HashMap<Object, String>;
    addressmap.put("address","Blah");
jsonRequest.put("address", addressMap);
jsonRequest.put("owner", OwnerMap);
jsonRequest.put("anotherThing", "thing");

返回为:

{
    "owner": {

    },
    "anotherThing": "thing",
    "address": {
        "address": "Blah"
    }
}

【问题讨论】:

  • 什么是 JSON 库?为什么不问问作者如何处理你的案子?
  • 如果您不使用库,您如何将 Hashmap 转换为 JSON?或者您是否在使用 GSON 或 Jackson 以外的其他库?

标签: java json hashmap rest-assured


【解决方案1】:

你似乎认为 inner(为了更好的词)Maps 必须是 Map&lt;*, String&gt;,而 MapString 是唯一的东西extend Object.

以下内容应该可以正常工作:

Map<String, Object> json = new HashMap<>();

Map<String, Object> customer = new HashMap<>();

// Could make this a Map<String, Object>[] (array) depending
// on json library used...  You don't specify.
List<Map<String, Object>> address = new ArrayList<>();
Map<String, Object> innerAddress = new HashMap<>();
innerAddress.put("address", "Blah");
address.add(innerAddress);

customer.put("address", address);

json.put("customer", customer);
json.put("anotherThing", "thing");

【讨论】:

  • 换一种说法,你的 customer.address 元素是一个 JSON 数组。所以你需要有一个该元素的地图列表。
  • ^ 那。另一种方法是根据需要制作 json 字符串并对其进行 de 序列化,然后检查输出结构。但同样,在不知道具体库的情况下,它可能只能序列化,而不能反序列化(尽管我会感到惊讶)。
  • 谢谢 Crig 和 BeUndead!这行得通。
  • 很高兴听到@CatAndPlantGuy。如果它解决了您的问题,请随时接受答案。 ??
猜你喜欢
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-12
  • 1970-01-01
相关资源
最近更新 更多