使用杰克逊创建一个 json 对象

Creating a json object using jackson(使用杰克逊创建一个 json 对象)
本文介绍了使用杰克逊创建一个 json 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 jackson 创建一个 json 数组,如下例所示.

How can I create a json array like the example below using jackson.

我尝试使用 ObjectMapper,但这似乎不正确.

I tried using ObjectMapper, but this does not seem correct.

      try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
            for (Path file : ds) {
                System.out.println("name:"+file.getFileName()+
                        "
"+
                        "mime:"+Files.probeContentType(file)+
                "
"+
                "locked:"+!Files.isWritable(file));
            }
        } catch (IOException e) {
            System.err.println(e);
        }

最终我将制作一个具有以下值的 json.

Eventually I will be making a json that has the below values.

 * - (int)    size    file size in b. required
 * - (int)    ts      file modification time in unix time. required
 * - (string) mime    mimetype. required for folders, others - optionally
 * - (bool)   read    read permissions. required
 * - (bool)   write   write permissions. required
 * - (bool)   locked  is object locked. optionally
 * - (bool)   hidden  is object hidden. optionally
 * - (string) alias   for symlinks - link target path relative to root path. optionally
 * - (string) target  for symlinks - link target path. optionally

这是我提供的一个示例 json.

Here is an example json I was provided.

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

编辑 1

        Map<String, Object> filesMap = new HashMap<>();
        List<Object> files = new ArrayList<Object>();
        System.out.println("
No filter applied:");
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
            for (Path file : ds) {
                Map<String, Object> fileInfo = new HashMap<>();
                fileInfo.put("name", file.getFileName().toString());
//                Prints Files in Director
//                Files.getAttribute(file,"size");
                System.out.println("name:" + file.getFileName().toString() +
                        "
" +
                        "mime:" + Files.probeContentType(file) +
                        "
" +
                        "locked:" + !Files.isWritable(file));
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(fileInfo);
                files.add(json);
            }
        } 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";  //To change body of catch statement use File | Settings | File Templates.
        }

输出以下更接近的json,但我无法弄清楚为什么{}之前和之后的额外引号.

Puts out the following json which is closer, but I can't figure out why the extra quotes before and after the {}.

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

最终答案

    Map<String, Object> filesMap = new HashMap<>();
    List<Object> files = new ArrayList<Object>();
    System.out.println("
No filter applied:");
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
        for (Path file : ds) {
            Map<String, Object> fileInfo = new HashMap<>();
            fileInfo.put("name", file.getFileName().toString());
            System.out.println("name:" + file.getFileName().toString() +
                    "
" +
                    "mime:" + Files.probeContentType(file) +
                    "
" +
                    "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"; 
    }

推荐答案

你需要一个 JsonNodeFactory:

You need a JsonNodeFactory:

final JsonNodeFactory factory = JsonNodeFactory.instance;

该类具有创建ArrayNodes、ObjectNodes、IntNodes、DecimalNodes、TextNode 之类的.ArrayNodes 和 ObjectNodes 具有方便的突变方法,可以直接添加大多数 JSON 原始(非容器)值,而无需通过工厂(嗯,在内部,它们引用了这个工厂),这就是为什么).

This class has methods to create ArrayNodes, ObjectNodes, IntNodes, DecimalNodes, TextNodes and whatnot. ArrayNodes and ObjectNodes have convenience mutation methods for adding directly most JSON primitive (non container) values without having to go through the factory (well, internally, they reference this factory, that is why).

对于ObjectMapper,注意它既是序列化器(ObjectWriter)又是反序列化器(ObjectReader).

As to an ObjectMapper, note that it is both a serializer (ObjectWriter) and deserializer (ObjectReader).

这篇关于使用杰克逊创建一个 json 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to get large JSON Using REST template Spring MVC without memory issues in java(如何在Java中无内存问题地使用REST模板Spring MVC获取大型JSON)
Using RestTemplate to map JSON to object(使用RestTemplate将JSON映射到对象)
How to map dynamic JSON in JAX-RS(如何在JAX-RS中映射动态JSON)
Convert tuples to json using rdf4j(使用rdf4j将元组转换为json)
How can I store nested JSON data in Room Database? [Room](如何将嵌套的JSON数据存储在Room Database中?[房间])
Is there any way to flatten the nested JSON in spark streaming?(有什么办法可以扁平化电光流媒体中的嵌套JSON吗?)