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

mzmfm0qo  于 2023-01-14  发布在  Java
关注(0)|答案(3)|浏览(209)

我有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
bhmjp9jg

bhmjp9jg1#

你可以使用Jackson库中的JavaPropsMapper,但是你必须在使用它之前定义接收json对象的对象层次结构,以便能够解析json字符串并从它构造java对象。
一旦你成功地从json构造了一个java对象,你就可以把它转换成Properties对象,然后你可以把它序列化成一个文件,这将创建你想要的。
示例json:

{ "title" : "Home Page", 
  "site"  : { 
        "host" : "localhost"
        "port" : 8080 ,
        "connection" : { 
            "type" : "TCP",
            "timeout" : 30 
        } 
    } 
}

以及Map上述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文件后,可以看到输出:
站点.连接.类型=TCP
站点连接超时=30
站点端口=8080
site.host=本地主机
title=主页
创意来自this文章。
希望这会有帮助。

vyswwuz2

vyswwuz22#

您可以遍历树并获得点标记中的属性。
下面是一个遍历树的示例

//------------ 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));
46scxncf

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);

相关问题