我有JSON字符串,并希望转换成java属性文件。JSON可以是JSON字符串、对象或文件。示例JSON:
{
"simianarmy": {
"chaos": {
"enabled": "true",
"leashed": "false",
"ASG": {
"enabled": "false",
"probability": "6.0",
"maxTerminationsPerDay": "10.0",
"IS": {
"enabled": "true",
"probability": "6",
"maxTerminationsPerDay": "100.0"
}
}
}
}
}
**OUTPUT SHOULD BE:-**
simianarmy.chaos.enabled=true
simianarmy.chaos.leashed=false
simianarmy.chaos.ASG.enabled=false
simianarmy.chaos.ASG.probability=6.0
simianarmy.chaos.ASG.maxTerminationsPerDay=10.0
simianarmy.chaos.ASG.IS.enabled=true
simianarmy.chaos.ASG.IS.probability=6
simianarmy.chaos.ASG.IS.maxTerminationsPerDay=100.0
3条答案
按热度按时间bhmjp9jg1#
你可以使用Jackson库中的
JavaPropsMapper
,但是你必须在使用它之前定义接收json对象的对象层次结构,以便能够解析json字符串并从它构造java对象。一旦你成功地从json构造了一个java对象,你就可以把它转换成
Properties
对象,然后你可以把它序列化成一个文件,这将创建你想要的。示例json:
以及Map上述JSON结构的类层次结构:
因此,您可以从中构造java对象
Endpoint
,并将其转换为Properties
对象,然后您可以将其序列化为.properties
文件:打开
json.properties
文件后,可以看到输出:站点.连接.类型=TCP
站点连接超时=30
站点端口=8080
site.host=本地主机
title=主页
创意来自this文章。
希望这会有帮助。
vyswwuz22#
您可以遍历树并获得点标记中的属性。
下面是一个遍历树的示例
示例用法:
下面是一个使用队列代替递归的迭代版本。
其中队列存储以下对象:
示例用法:
46scxncf3#
还支持嵌套JSON
ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Map<Object, Object> map = objectMapper.readValue(jsonString,new TypeReference<Map<Object, Object>>() {}); JavaPropsMapper mapper = new JavaPropsMapper(); Properties props = mapper.writeValueAsProperties(map); System.out.println(props);