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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With