我有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
答案 0 :(得分:3)
您可以遍历树并以点表示法获取属性。
例如:这是示例树遍历
//------------ Transform jackson JsonNode to Map -----------
public static Map<String, String> transformJsonToMap(JsonNode node, String prefix){
Map<String,String> jsonMap = new HashMap<>();
if(node.isArray()) {
//Iterate over all array nodes
int i = 0;
for (JsonNode arrayElement : node) {
jsonMap.putAll(transformJsonToMap(arrayElement, prefix+"[" + i + "]"));
i++;
}
}else if(node.isObject()){
Iterator<String> fieldNames = node.fieldNames();
String curPrefixWithDot = (prefix==null || prefix.trim().length()==0) ? "" : prefix+".";
//list all keys and values
while(fieldNames.hasNext()){
String fieldName = fieldNames.next();
JsonNode fieldValue = node.get(fieldName);
jsonMap.putAll(transformJsonToMap(fieldValue, curPrefixWithDot+fieldName));
}
}else {
//basic type
jsonMap.put(prefix,node.asText());
System.out.println(prefix+"="+node.asText());
}
return jsonMap;
}
示例用法:
//--- Eg: --------------
String SAMPLE_JSON_DATA = "{\n" +
" \"data\": {\n" +
" \"firstName\": \"Spider\",\n" +
" \"lastName\": \"Man\",\n" +
" \"age\": 21,\n" +
" \"cars\":[ \"Ford\", \"BMW\", \"Fiat\" ]\n" +
" }\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
Map props = transformJsonToMap(objectMapper.readTree(SAMPLE_JSON_DATA),null);
System.out.println(props.toString());
//-----output : --------------------------------
data.firstName=Spider
data.lastName=Man
data.age=21
data.cars[0]=Ford
data.cars[1]=BMW
data.cars[2]=Fiat
{data.cars[2]=Fiat, data.cars[1]=BMW, data.cars[0]=Ford, data.lastName=Man, data.age=21, data.firstName=Spider}
//-------------
这是一个使用队列而不是递归的迭代版本。
//------------ Transform jackson JsonNode to Map -Iterative version -----------
public static Map<String,String> transformJsonToMapIterative(JsonNode node){
Map<String,String> jsonMap = new HashMap<>();
LinkedList<JsonNodeWrapper> queue = new LinkedList<>();
//Add root of json tree to Queue
JsonNodeWrapper root = new JsonNodeWrapper(node,"");
queue.offer(root);
while(queue.size()!=0){
JsonNodeWrapper curElement = queue.poll();
if(curElement.node.isObject()){
//Add all fields (JsonNodes) to the queue
Iterator<Map.Entry<String,JsonNode>> fieldIterator = curElement.node.fields();
while(fieldIterator.hasNext()){
Map.Entry<String,JsonNode> field = fieldIterator.next();
String prefix = (curElement.prefix==null || curElement.prefix.trim().length()==0)? "":curElement.prefix+".";
queue.offer(new JsonNodeWrapper(field.getValue(),prefix+field.getKey()));
}
}else if (curElement.node.isArray()){
//Add all array elements(JsonNodes) to the Queue
int i=0;
for(JsonNode arrayElement : curElement.node){
queue.offer(new JsonNodeWrapper(arrayElement,curElement.prefix+"["+i+"]"));
i++;
}
}else{
//If basic type, then time to fetch the Property value
jsonMap.put(curElement.prefix,curElement.node.asText());
System.out.println(curElement.prefix+"="+curElement.node.asText());
}
}
return jsonMap;
}
队列存储对象的位置:
class JsonNodeWrapper{
public JsonNode node;
public String prefix;
public JsonNodeWrapper(JsonNode node, String prefix){
this.node = node;
this.prefix = prefix;
}
}
示例用法:
Map propsIterative = transformJsonToMapIterative(objectMapper.readTree(SAMPLE_JSON_DATA));
答案 1 :(得分:0)
您可以从杰克逊图书馆使用JavaPropsMapper
。但是,您必须先定义接收方json对象的对象层次结构,然后才能使用它,以便能够解析json字符串并从中构造java对象。
一旦从json成功构造了一个Java对象,就可以将其转换为Properties
对象,然后可以将其序列化为文件,这将创建所需的内容。
示例json:
{ "title" : "Home Page",
"site" : {
"host" : "localhost"
"port" : 8080 ,
"connection" : {
"type" : "TCP",
"timeout" : 30
}
}
}
以及用于映射上述JSON结构的类层次结构:
class Endpoint {
public String title;
public Site site;
}
class Site {
public String host;
public int port;
public Connection connection;
}
class Connection{
public String type;
public int timeout;
}
因此,您可以从中构造Java对象Endpoint
并转换为Properties
对象,然后可以序列化为.properties
文件:
public class Main {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String json = "{ \"title\" : \"Home Page\", "+
"\"site\" : { "+
"\"host\" : \"localhost\", "+
"\"port\" : 8080 , "+
"\"connection\" : { "+
"\"type\" : \"TCP\","+
"\"timeout\" : 30 "+
"} "+
"} "+
"}";
ObjectMapper om = new ObjectMapper();
Endpoint host = om.readValue(json, Endpoint.class);
JavaPropsMapper mapper = new JavaPropsMapper();
Properties props = mapper.writeValueAsProperties(host);
props.store(new FileOutputStream(new File("/path_to_file/json.properties")), "");
}
}
打开json.properties
文件后,您将看到输出:
site.connection.type = TCP
site.connection.timeout = 30
site.port = 8080
site.host =本地主机
title =主页
该想法来自this文章。
希望这会有所帮助。