0

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.

nour nour
  • 85
  • 1
  • 2
  • 9

3 Answers3

3

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());
Radouane ROUFID
  • 10,595
  • 9
  • 42
  • 80
1

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.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
1

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());
    }
Luciano
  • 2,695
  • 6
  • 38
  • 53
rootExplorr
  • 575
  • 3
  • 17