programing

Jackson을 사용하여 json 개체 만들기

magicmemo 2023. 3. 12. 10:39
반응형

Jackson을 사용하여 json 개체 만들기

Jackson을 사용하여 아래 예시와 같은 json 배열을 작성하려면 어떻게 해야 합니까?

Object Mapper를 사용해 봤는데 잘못된 것 같아요.

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

필요한 것은 다음과 같습니다.

final JsonNodeFactory factory = JsonNodeFactory.instance;

이 클래스에는 만들 메서드가 있습니다.ArrayNodes,ObjectNodes,IntNodes,DecimalNodes,TextNode뭐 그런 거. ArrayNodeObjectNode에는 공장을 통하지 않고 대부분의 JSON 원시(비컨테이너) 값을 직접 추가할 수 있는 편리한 변환 방법이 있습니다(내부적으로는 이 공장을 참조하고 있습니다).

에 대해서ObjectMapper양쪽 모두 시리얼라이저인 것에 주의해 주세요).ObjectWriter및 디시리얼라이저(ObjectReader).

json 문자열에 개체를 쓸 수 있습니다.따라서 필요에 따라 정의된 클래스의 객체에 데이터를 저장해야 합니다.다음은 해당 개체를 json 문자열로 변환하는 방법입니다.

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

String jsonString = mapper.writeValueAsString(yourObject);

jackson-databackson-databind javadoc

JSON 오브젝트를 싱글톤인스턴스로 초기화하고 빌드합니다.

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

PS: 인쇄하기node.toString().

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);

언급URL : https://stackoverflow.com/questions/16974474/creating-a-json-object-using-jackson

반응형