首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java中将JSON转换为属性文件?

如何在java中将JSON转换为属性文件?
EN

Stack Overflow用户
提问于 2019-01-20 14:27:18
回答 2查看 7K关注 0票数 0

我有JSON字符串,并想转换成java属性文件。注意: JSON可以是JSON字符串、对象或文件。示例JSON:

代码语言:javascript
复制
{
    "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
EN

回答 2

Stack Overflow用户

发布于 2019-01-20 17:30:53

你可以使用jackson库中的JavaPropsMapper。但是您必须先定义接收json对象的对象层次结构,然后才能使用它,以便能够解析json字符串并从它构造java对象。

一旦从json成功构建了java对象,就可以将其转换为Properties对象,然后可以将其序列化为文件,这将创建所需的内容。

示例json:

代码语言:javascript
复制
{ "title" : "Home Page", 
  "site"  : { 
        "host" : "localhost"
        "port" : 8080 ,
        "connection" : { 
            "type" : "TCP",
            "timeout" : 30 
        } 
    } 
}

以及映射上述JSON结构的类层次结构:

代码语言:javascript
复制
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文件:

代码语言:javascript
复制
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页面

这个想法来自this的文章。

希望这能对你有所帮助。

票数 3
EN

Stack Overflow用户

发布于 2020-07-07 09:42:13

您可以进行树遍历并以点表示法获取属性。

这是一个遍历树的示例

代码语言:javascript
复制
//------------ 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;
}

示例用法:

代码语言:javascript
复制
//--- 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}
//-------------

这是一个使用队列而不是递归的迭代版本。

代码语言:javascript
复制
//------------ 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;
}

其中,queue存储以下对象:

代码语言:javascript
复制
class JsonNodeWrapper{

    public JsonNode node;
    public String prefix;

    public JsonNodeWrapper(JsonNode node, String prefix){
        this.node = node;
        this.prefix = prefix;
    }

}

示例用法:

代码语言:javascript
复制
Map propsIterative = transformJsonToMapIterative(objectMapper.readTree(SAMPLE_JSON_DATA));
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54274134

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档