我想将Java属性文件转换为带有嵌套对象的JSON。我按照一个发现here的示例进行操作,但无法正常工作。
例如,给定:
objectA.version=1.0
objectA.hostname=192.168.0.11
objectA.port=9989
objectB.hostname=10.0.2.15
objectB.port=9998
我想要:
{
“objectA” : {
"version” : "1.0"
"host” : “192.168.0.11”,
"port" : 9989
},
“objectB” : {
"host” : “10.0.2.15”,
"port" : 9998
}
}
这是我到目前为止的内容:
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);
}
输出如下所示:
objectA.version=1.0
objectA.hostname=192.168.0.11
objectA.port=9989
objectB.hostname=10.0.2.15
objectB.port=9998
最佳答案
我想到了。
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);
}