2

I have JSON string and want to convert into java properties file. Note: JSON can be in JSON string, object or file. Sample 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
8
  • Is there any fixed level of nested block? Jan 20, 2019 at 6:47
  • Have you made any attempt on your own? Jan 20, 2019 at 6:59
  • @krishnaPrasad no ,there is no fixed level of nested block. its dynamic Jan 20, 2019 at 7:00
  • @chrylis i tried using jackson library but i was unable to do that. Jan 20, 2019 at 7:01
  • So post the code that didn't work and explain specifically what didn't work, not just "I couldn't". Jan 20, 2019 at 7:02

3 Answers 3

6

You can use JavaPropsMapper from jackson library. But you must define the object hierarchy of the receiving json object before you can use it in order to be able to parse the json string and construct the java object from it.

Once you have a java object successfully constructed from json, you can convert it into the Properties object and then you can serialize it into a file and this will create what you want.

Example json:

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

And the class hierarchy to map the above JSON structure:

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

So you can construct the java object Endpoint from it and the convert into Properties object and then you can serialize into a .properties file:

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")), "");
    }
}

Once you open the json.properties file you can see the output:

site.connection.type=TCP

site.connection.timeout=30

site.port=8080

site.host=localhost

title=Home Page

The Idea came from this article.

Hope this would be helpful.

1
  • It is a good solution, but you don't need to have the class with json structure and you can simply use Object.class and it works perfectly. Oct 29, 2021 at 12:04
4

You can do a tree traversal and get the properties in a dot notation.

eg : Here is a sample tree traversal

//------------ 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;
}

Example usage :

//--- 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}
//-------------

Here is a iterative version using a queue instead of recursion.

//------------ 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;
}

Where queue stores objects of :

class JsonNodeWrapper{

    public JsonNode node;
    public String prefix;

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

}

Example Usage :

Map propsIterative = transformJsonToMapIterative(objectMapper.readTree(SAMPLE_JSON_DATA));
0

support also nested 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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.