001package org.json;
002
003/*
004Copyright (c) 2002 JSON.org
005
006Permission is hereby granted, free of charge, to any person obtaining a copy
007of this software and associated documentation files (the "Software"), to deal
008in the Software without restriction, including without limitation the rights
009to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
010copies of the Software, and to permit persons to whom the Software is
011furnished to do so, subject to the following conditions:
012
013The above copyright notice and this permission notice shall be included in all
014copies or substantial portions of the Software.
015
016The Software shall be used for Good, not Evil.
017
018THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
019IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
020FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
021AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
022LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
023OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
024SOFTWARE.
025*/
026
027import java.util.Enumeration;
028import java.util.Iterator;
029import java.util.Properties;
030
031/**
032 * Converts a Property file data into JSONObject and back.
033 * @author JSON.org
034 * @version 2015-05-05
035 */
036public class Property {
037    /**
038     * Converts a property file object into a JSONObject. The property file object is a table of name value pairs.
039     * @param properties java.util.Properties
040     * @return JSONObject
041     * @throws JSONException
042     */
043    public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException {
044        JSONObject jo = new JSONObject();
045        if (properties != null && !properties.isEmpty()) {
046            Enumeration<?> enumProperties = properties.propertyNames();
047            while(enumProperties.hasMoreElements()) {
048                String name = (String)enumProperties.nextElement();
049                jo.put(name, properties.getProperty(name));
050            }
051        }
052        return jo;
053    }
054
055    /**
056     * Converts the JSONObject into a property file object.
057     * @param jo JSONObject
058     * @return java.util.Properties
059     * @throws JSONException
060     */
061    public static Properties toProperties(JSONObject jo)  throws JSONException {
062        Properties  properties = new Properties();
063        if (jo != null) {
064            Iterator<String> keys = jo.keys();
065            while (keys.hasNext()) {
066                String name = keys.next();
067                properties.put(name, jo.getString(name));
068            }
069        }
070        return properties;
071    }
072}