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

Ani*_*wal 2 java json properties-file

我有 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
Run Code Online (Sandbox Code Playgroud)

STa*_*efi 6

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

一旦你成功地从 json 构造了一个 java 对象,你就可以将它转换为该Properties对象,然后你可以将它序列化到一个文件中,这将创建你想要的东西。

示例 json:

{ "title" : "Home Page", 
  "site"  : { 
        "host" : "localhost"
        "port" : 8080 ,
        "connection" : { 
            "type" : "TCP",
            "timeout" : 30 
        } 
    } 
}
Run Code Online (Sandbox Code Playgroud)

以及映射上述 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;
}
Run Code Online (Sandbox Code Playgroud)

Endpoint因此,您可以从中构造 java 对象并转换为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")), "");
    }
}
Run Code Online (Sandbox Code Playgroud)

打开json.properties文件后,您可以看到输出:

site.connection.type=TCP

站点.连接.超时=30

站点.端口=8080

站点.主机=本地主机

标题=主页

这个想法来自这篇文章。

希望这会有所帮助。