如何将 JSON 转换为 java 中的属性文件?
How to convert a JSON into properties file in java?
我有 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
您可以使用 jackson 库中的 JavaPropsMapper
。但是您必须在使用它之前定义接收 json 对象的对象层次结构,以便能够解析 json 字符串并从中构造 java 对象。
一旦你从json成功构造了一个java对象,你可以将它转换成Properties
对象,然后你可以将它序列化到一个文件中,这将创建什么你要。
示例json:
{ "title" : "Home Page",
"site" : {
"host" : "localhost"
"port" : 8080 ,
"connection" : {
"type" : "TCP",
"timeout" : 30
}
}
}
和 class 层次结构映射上面的 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=localhost
title=Home Page
想法来自 this 文章。
希望这会有所帮助。
您可以进行树遍历并获取点表示法中的属性。
例如:这是一个示例树遍历
//------------ 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));
我有 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
您可以使用 jackson 库中的 JavaPropsMapper
。但是您必须在使用它之前定义接收 json 对象的对象层次结构,以便能够解析 json 字符串并从中构造 java 对象。
一旦你从json成功构造了一个java对象,你可以将它转换成Properties
对象,然后你可以将它序列化到一个文件中,这将创建什么你要。
示例json:
{ "title" : "Home Page",
"site" : {
"host" : "localhost"
"port" : 8080 ,
"connection" : {
"type" : "TCP",
"timeout" : 30
}
}
}
和 class 层次结构映射上面的 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=localhost
title=Home Page
想法来自 this 文章。
希望这会有所帮助。
您可以进行树遍历并获取点表示法中的属性。
例如:这是一个示例树遍历
//------------ 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));