Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

java properties to json

Is there an easy way to convert properties with dot notation to json

I.E

server.host=foo.bar
server.port=1234

TO

{
 "server": {
    "host": "foo.bar",
    "port": 1234
  }
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not the easy way, but I managed to do that using Gson library. The result will be in the jsonBundle String. Here we getting the properties or bundles in this case:

final ResourceBundle bundle = ResourceBundle.getBundle("messages");
final Map<String, String> bundleMap = resourceBundleToMap(bundle);

final Type mapType = new TypeToken<Map<String, String>>(){}.getType();

final String jsonBundle = new GsonBuilder()
        .registerTypeAdapter(mapType, new BundleMapSerializer())
        .create()
        .toJson(bundleMap, mapType);

For this implementation ResourceBundle have to be converted to Map containing String as a key and String as a value.

private static Map<String, String> resourceBundleToMap(final ResourceBundle bundle) {
    final Map<String, String> bundleMap = new HashMap<>();

    for (String key: bundle.keySet()) {
        final String value = bundle.getString(key);

        bundleMap.put(key, value);
    }

    return bundleMap;
}

I had to create custom JSONSerializer using Gson for Map<String, String>:

public class BundleMapSerializer implements JsonSerializer<Map<String, String>> {

    private static final Logger LOGGER = LoggerFactory.getLogger(BundleMapSerializer.class);

    @Override
    public JsonElement serialize(final Map<String, String> bundleMap, final Type typeOfSrc, final JsonSerializationContext context) {
        final JsonObject resultJson =  new JsonObject();

        for (final String key: bundleMap.keySet()) {
            try {
                createFromBundleKey(resultJson, key, bundleMap.get(key));
            } catch (final IOException e) {
                LOGGER.error("Bundle map serialization exception: ", e);
            }
        }

        return resultJson;
    }
}

And here is the main logic of creating JSON:

public static JsonObject createFromBundleKey(final JsonObject resultJson, final String key, final String value) throws IOException {
    if (!key.contains(".")) {
        resultJson.addProperty(key, value);

        return resultJson;
    }

    final String currentKey = firstKey(key);
    if (currentKey != null) {
        final String subRightKey = key.substring(currentKey.length() + 1, key.length());
        final JsonObject childJson = getJsonIfExists(resultJson, currentKey);

        resultJson.add(currentKey, createFromBundleKey(childJson, subRightKey, value));
    }

    return resultJson;
}

    private static String firstKey(final String fullKey) {
        final String[] splittedKey = fullKey.split("\.");

        return (splittedKey.length != 0) ? splittedKey[0] : fullKey;
    }

    private static JsonObject getJsonIfExists(final JsonObject parent, final String key) {
        if (parent == null) {
            LOGGER.warn("Parent json parameter is null!");
            return null;
        }

        if (parent.get(key) != null && !(parent.get(key) instanceof JsonObject)) {
            throw new IllegalArgumentException("Invalid key '" + key + "' for parent: " + parent + "
Key can not be JSON object and property or array in one time");
        }

        if (parent.getAsJsonObject(key) != null) {
            return parent.getAsJsonObject(key);
        } else {
            return new JsonObject();
        }
   }

In the end, if there were a key person.name.firstname with value John, it will be converted to such JSON:

{
     "person" : {
         "name" : {
             "firstname" : "John"
         }
     }
}

Hope this will help :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...