我有一个数组列表多 map -
ArrayListMultimap<String, String> fcmbuildProperties = ArrayListMultimap.create();
ArrayListMultimap<String, String> scm = ArrayListMultimap.create();
//HashMap<String, String> fcmbuildProperties= new HashMap<String, String>();
fcmbuildProperties.put("name", buildName);
fcmbuildProperties.put("timestamp", buildTimeStamp);
fcmbuildProperties.put("groupId", groupID);
fcmbuildProperties.put("artifactId", artifactID);
fcmbuildProperties.put("version", version);
fcmbuildProperties.put("environment", environment);
fcmbuildProperties.put("number", patch);
fcmbuildProperties.put("artifactPath", layoutPath);
fcmbuildProperties.put("architecture", architecture);
fcmbuildProperties.put("operatingSystem", operatingSystem);
scm.put("commit",commitSha);
scm.put("url", githubUrl);
scm.put("branch", githubBranch);
这显示为 json,如下所示:
{
"operatingSystem": [
"rhel5"
],
"artifactPath": [
"djin/platform/cache/test/rhel5/i386/packages/test/test-1.0.0-d.284.i386.rpm"
],
"artifactId": [
"test"
],
"number": [
"284"
],
"architecture": [
"i386"
],
"url": [
null
],
"version": [
"1.0.0"
],
"timestamp": [
"6/4/15/2015/11:22:7"
],
"groupId": [
"cache"
],
"environment": [
"snapshot"
],
"commit": [
null
],
"name": [
"fcm-dummy-web"
],
"branch": [
null
]
}
但是我需要如何将其解析为:
{
"name": "fcm-dummy-web",
"url": "job/fcm-dummy-web/",
"build": {
"full_url": "job/fcm-dummy-web/29/",
"number": 38,
"url": "job/fcm-dummy-web/29/",
"scm": {
"url": "institutional/fcm-dummy-web",
"branch": "origin/master",
"commit": "989f0b78470f0dc9e262cc020e66837beef16c4e"
},
"artifacts": {
"id": "test",
"groupId": "djin/platform/cache",
"operatingSystem": "rhel5",
"environment": "snapshot",
"path": "/cache/test/rhel5/i386/packages/testtest-1.0.0-d.269.i386.msi",
"architecture": "i386",
"version": "1.0.0"
}
}
}
嵌套的 json 比平面结构更多。进行此操作的有效方法是什么?
我使用 gson 从 arrayListMultimap 中生成儿子:
Gson gson = new Gson();
String jsonString = gson.toJson(fcmbuildProperties.asMap());
最佳答案
这取决于您使用哪个库进行 JSON 序列化。
许多库提供“ pretty-print ”,这是一个常见的属性:
Pretty printing JSON from Jackson 2.2's ObjectMapper
编辑:使用 Gson 很简单
Gson gson = new GsonBuilder().setPrettyPrinting().create();
创建Gson对象时。
编辑2:
public static class OuterObject {
String name;
String url;
BuildProperties properties;
}
public static class BuildProperties {
String full_url;
int number;
Map<String, String> scm = new HashMap<String, String>() {{
put("url":"institutional/fcm-dummy-web");
//etc
}};
}
关于java - 在java中从数组列表多映射创建嵌套Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30263491/