使用jackson创建一个json对象
使用jackson创建一个json对象
如何使用jackson创建一个像下面示例的json数组。
我尝试使用ObjectMapper,但这似乎不正确。
try (DirectoryStreamds = Files.newDirectoryStream(path)) { for (Path file : ds) { System.out.println("name:"+file.getFileName()+ "\n"+ "mime:"+Files.probeContentType(file)+ "\n"+ "locked:"+!Files.isWritable(file)); } } catch (IOException e) { System.err.println(e); }
最终我将创建一个具有以下值的json。
* - (int) size 文件大小(以字节为单位)。必需 * - (int) ts 文件修改时间(Unix时间)。必需 * - (string) mime mimetype。文件夹必需,其他可选 * - (bool) read 读权限。必需 * - (bool) write 写权限。必需 * - (bool) locked 对象是否被锁定。可选 * - (bool) hidden 对象是否隐藏。可选 * - (string) alias 对于符号链接 - 相对于根路径的链接目标路径。可选 * - (string) target 对于符号链接 - 链接目标路径。可选
这是我所提供的示例json。
"files": [
{
"mime": "directory",
"ts": 1334071677,
"read": 1,
"write": 0,
"size": 0,
"hash": "l1_Lw",
"volumeid": "l1_",
"name": "Demo",
"locked": 1,
"dirs": 1
},
{
"mime": "directory",
"ts": 1334071677,
"read": 1,
"write": 0,
"size": 0,
"hash": "l1_Lw",
"volumeid": "l1_",
"name": "Demo",
"locked": 1,
"dirs": 1
},
{
"mime": "directory",
"ts": 1340114567,
"read": 0,
"write": 0,
"size": 0,
"hash": "l1_QmFja3Vw",
"name": "Backup",
"phash": "l1_Lw",
"locked": 1
},
{
"mime": "directory",
"ts": 1310252178,
"read": 1,
"write": 0,
"size": 0,
"hash": "l1_SW1hZ2Vz",
"name": "Images",
"phash": "l1_Lw",
"locked": 1
},
{
"mime": "application\/x-genesis-rom",
"ts": 1310347586,
"read": 1,
"write": 0,
"size": 3683,
"hash": "l1_UkVBRE1FLm1k",
"name": "README.md",
"phash": "l1_Lw",
"locked": 1
}
]
EDIT 1
MapfilesMap = new HashMap<>(); List
输出了以下更接近的json,但我无法弄清楚为什么在{}之前和之后有额外的引号。
{"files":["{\"name\":\"32C92124-EFCF-42C1-AFD2-8B741AE6854B.jpg\"}","{\"name\":\"58D5B83F-4065-4D6E-92BE-8181D99CB6CB.jpg\"}","{\"name\":\"7B1464A0-FBA1-429E-8A39-3DE5B539FBF8.jpg\"}","{\"name\":\"888159CF-45BE-475F-8C6A-64B3E1D97278.jpg\"}"]}
最终答案
MapfilesMap = new HashMap<>(); List files = new ArrayList (); System.out.println("\nNo filter applied:"); try (DirectoryStream ds = Files.newDirectoryStream(path)) { for (Path file : ds) { Map fileInfo = new HashMap<>(); fileInfo.put("name", file.getFileName().toString()); System.out.println("name:" + file.getFileName().toString() + "\n" + "mime:" + Files.probeContentType(file) + "\n" + "locked:" + !Files.isWritable(file)); files.add(fileInfo); } } catch (IOException e) { System.err.println(e); } files.toArray(); filesMap.put("files", files); ObjectMapper mapper = new ObjectMapper(); String jsonString; try { jsonString = mapper.writeValueAsString(filesMap); } catch (IOException e) { jsonString = "fail"; }