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.

1

3 Answers 3

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());
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.