使用HashMap创建复数JSON

Using HashMap to create complex JSON

我花了几天时间在谷歌上搜索各种方式,但没有看到任何给出使用 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");

returns 为:

{
    "owner": {

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

您似乎假设 inner(需要一个更好的词)Maps 需要是 Map<*, String>,并且 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");