使用jackson创建json对象

时间:2013-06-07 00:36:52

标签: java json hashmap jackson

如何使用jackson创建类似下面示例的json数组。

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

      try (DirectoryStream<Path> ds = 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    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示例。

"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("\nNo 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() +
                        "\n" +
                        "mime:" + Files.probeContentType(file) +
                        "\n" +
                        "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,但我无法弄清楚为什么{}之前和之后的额外引号。

{"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("\nNo 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() +
                    "\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"; 
    }

4 个答案:

答案 0 :(得分:45)

您需要JsonNodeFactory

final JsonNodeFactory factory = JsonNodeFactory.instance;

此类包含创建ArrayNodeObjectNodeIntNodeDecimalNodeTextNode和其他内容的方法。 ArrayNodeObjectNode具有方便变异方法,可以直接添加大多数JSON原语(非容器)值而无需经过工厂(在内部,它们引用此工厂,这就是原因)。

对于ObjectMapper,请注意它既是序列化程序(ObjectWriter)又是反序列化程序(ObjectReader)。

答案 1 :(得分:13)

您可以将对象写入json字符串。因此,我希望您将数据放在根据您的需要定义的类的对象中。以下是将该对象转换为json字符串的方法:

//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();

String jsonString = mapper.writeValueAsString(yourObject);

有关完整的jackson-databind javadoc,请参阅here

答案 2 :(得分:10)

您可以在不创建POJO并将其转换为JSON的情况下执行此操作。我假设您的数据在Record对象中。

        JsonNode rootNode = mapper.createObjectNode();
        ArrayNode childNodes = mapper.createArrayNode();
        for (Record record : records) {
            JsonNode element = mapper.createObjectNode();
            ((ObjectNode) element).put("mime": record.getDirectory());
                  //fill rest of fields which are needed similar to this.
                  //Also here record.getDirectory() method will should return "directory"
                  //according to your json file.
            childNodes.add(element);
        }
        ((ObjectNode) rootNode).put("files", childNodes);

答案 3 :(得分:8)

将JSON对象初始化为单例实例,并构建它:

ObjectNode node = JsonNodeFactory.instance.objectNode(); // initializing
node.put("x", x); // building

PS:打印使用node.toString()