I would like to convert a Java Properties file into JSON with nested objects. I followed an example I found here but I can't get it to work.
For example, given:
objectA.version=1.0
objectA.hostname=192.168.0.11
objectA.port=9989
objectB.hostname=10.0.2.15
objectB.port=9998
I want:
{
“objectA” : {
"version” : "1.0"
"host” : “192.168.0.11”,
"port" : 9989
},
“objectB” : {
"host” : “10.0.2.15”,
"port" : 9998
}
}
This is what I have so far:
static class Endpoint
{
@JsonProperty("objectA")
public ObjectA objectA;
@JsonProperty("objectB")
public ObjectB objectB;
}
static class ObjectA
{
public String hostname;
public String port;
public String version;
}
static class ObjectB
{
public String hostname;
public String port;
}
try (InputStream input = getClass().getClassLoader().getResourceAsStream("file.properties"))
{
JavaPropsMapper mapper = new JavaPropsMapper();
Endpoint host = mapper.readValue(input, Endpoint.class);
String asText = mapper.writeValueAsString(host);
System.out.println(asText);
}
The output looks like this:
objectA.version=1.0
objectA.hostname=192.168.0.11
objectA.port=9989
objectB.hostname=10.0.2.15
objectB.port=9998
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. Eg
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.