nour nour
nour nour

Reputation: 95

Display properties file elements as a json array

I want to display what I have the properties file as a json array: Here's my java code:

props.setProperty("Info1", "stack1");
props.setProperty("Info2", "stack2");

What I got in properties file:

 Info1=stack1
 Info2=stack2

Here's what want to get

var Obj =  {}
Obj.dataset= [{ "Info1":"stack1" },{ "Info2"="stack2"}];

I tried with Gson and JsonObject but in vain. What should I do please? It's not a duplicate question because I am using properties class and the suggested answers that I have already tried didn't work.

Upvotes: 0

Views: 829

Answers (3)

rootExplorr
rootExplorr

Reputation: 575

You can also use the following:

    Properties props = new Properties();
    props.setProperty("Info1", "stack1");
    props.setProperty("Info2", "stack2");
    JSONArray array = new JSONArray();
    Map map = new HashMap();

    Iterator iter = props.keySet().iterator();

    while (iter.hasNext()) {
        String key = (String) iter.next();
        String value = props.getProperty(key);
        map.put(key, value);
    }

    array.put(map);
    for (int i = 0; i < array.length(); i++) {
        JSONObject obj = (JSONObject) array.get(i);
        System.out.println(obj.toString());
    }

Upvotes: 1

Radouane ROUFID
Radouane ROUFID

Reputation: 10813

You can loop over properties and add the key/value to a Json Array as below:

Properties props = new Properties();
props.setProperty("Info1", "stack1");
props.setProperty("Info2", "stack2");

Enumeration e = props.propertyNames();
JsonArray  jsonArray = new JSONArray();

while(e.hasMoreElements()) {
    String key = (String) e.nextElement();
    String value = props.getProperty(key);

    JSONObject jsonObject = new JSONObject();
    jsonObject.put(key, value);

    jsonArray.add(jsonObject);
}

System.out.println(jsonArray.toString());

Upvotes: 3

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

It can be done with jackson and its ObjectMapper like this:

Properties props = new Properties();
props.setProperty("Info1", "stack1");
props.setProperty("Info2", "stack2");

ObjectMapper mapper = new ObjectMapper();
StringWriter writer = new StringWriter();
mapper.writeValue(writer, props);
System.out.println(writer.toString());

Output:

{"Info2":"stack2","Info1":"stack1"}

Here is a good tutorial about Jackson.

Upvotes: 1

Related Questions