Java Properties file to JSON using Jackson Java Properties file to JSON using Jackson json json

Java Properties file to JSON using Jackson


I figured it out.

try (InputStream input = getClass().getClassLoader().getResourceAsStream("file.properties")){    JavaPropsMapper mapper = new JavaPropsMapper();    Endpoint host = mapper.readValue(input, Endpoint.class);    // String asText = mapper.writeValueAsString(host);    // add this    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();    String asText = ow.writeValueAsString(host);    //     System.out.println(asText);}


Not sure if the OP needs an interim object OR if he just wants to get from a props file to a JSON representation of it. If it is the latter then it's easier to just use the databind ObjectNode class as the interim. E.g.

try (InputStream input = new FileInputStream("path_to.properties")) {    JavaPropsMapper mapper = new JavaPropsMapper();    ObjectNode node = mapper.readValue(input, ObjectNode.class);    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();    // Alternatively write to file ???    System.out.println(ow.writeValueAsString(node);} catch (IOException e) {    // Do something}