使用HashMap创建复杂的JSON



我花了几天时间在谷歌上搜索了各种方法,但没有看到任何使用HashMap的例子-相反,它们都指的是Jackson或GSON。我无法使用这些,因为它们会导致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稍微复杂一点,我似乎无法弄清楚…I不能使用任何其他依赖项。

如果我有一个JSON Body需要发送:

{
"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"
}
}

你似乎认为内部(为了找一个更好的词)Maps需要是Map<*, String>,MapStringextend 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");

最新更新