les propriétés java de json

y a-t-il un moyen facile de convertir les propriétés avec la notation de point en json

I. E

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

{
 "server": {
    "host": "foo.bar",
    "port": 1234
  }
} 
22
demandé sur Roman C 2014-05-26 17:50:01

7 réponses

pas facile, mais j'ai réussi à le faire en utilisant Gson bibliothèque. Le résultat sera dans le jsonBundle Chaîne de caractères. Ici nous obtenons les propriétés ou les paquets dans ce cas:

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

Pour cette mise en œuvre ResourceBundle être converti en Map contenant String comme une clé et String en tant que valeur.

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

j'ai eu à le créer sur mesure JSONSerializer en utilisant GsonMap<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;
    }
}

Et voici la principale logique de la création 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 + "\nKey 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();
        }
   }

En fin de compte, si il y avait une clé person.name.firstname valeur John, il sera converti en tel JSON:

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

Espérons que cela aide :)

6
répondu Yuriy Yunikov 2014-11-04 08:10:02

il est assez facile, télécharger et ajouter à votre lib: https://code.google.com/p/google-gson/

Gson gsonObj = new Gson();
String strJson =  gsonObj.toJson(yourObject);
2
répondu klapvee 2014-05-26 13:58:00

Regarde ce https://github.com/nzakas/props2js. Vous pouvez l'utiliser manuellement ou à la fourche et à utiliser dans votre projet.

0
répondu Ostap Maliuvanchuk 2014-05-26 14:31:11

Un peu de récursivité et de Gson :)

public void run() throws IOException {

    Properties properties = ...;

    Map<String, Object> map = new TreeMap<>();

    for (Object key : properties.keySet()) {
        List<String> keyList = Arrays.asList(((String) key).split("\."));
        Map<String, Object> valueMap = createTree(keyList, map);
        String value = properties.getProperty((String) key);
        value = StringEscapeUtils.unescapeHtml(value);
        valueMap.put(keyList.get(keyList.size() - 1), value);
    }

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(map);

    System.out.println("Ready, converts " + properties.size() + " entries.");
}

@SuppressWarnings("unchecked")
private Map<String, Object> createTree(List<String> keys, Map<String, Object> map) {
    Map<String, Object> valueMap = (Map<String, Object>) map.get(keys.get(0));
    if (valueMap == null) {
        valueMap = new HashMap<String, Object>();
    }
    map.put(keys.get(0), valueMap);
    Map<String, Object> out = valueMap;
    if (keys.size() > 2) {
        out = createTree(keys.subList(1, keys.size()), valueMap);
    }
    return out;
}
0
répondu Mark 2016-03-11 11:36:58

Je ne voulais pas de dépendance sur gson et je voulais rendre un JSON hiérarchique d'un contrôleur de printemps donc une carte profonde était suffisante pour moi.

cela fonctionne pour moi, juste boucler toutes vos clés et passer dans une carte vide.

void recurseCreateMaps(Map<String, Object> currentMap, String key, String value) {
    if (key.contains(".")) {
        String currentKey = key.split("\.")[0];

        Map<String, Object> deeperMap;

        if (currentMap.get(currentKey) instanceof Map) {
            deeperMap = (Map<String, Object>) currentMap.get(currentKey);
        } else {
            deeperMap = new HashMap<>();
            currentMap.put(currentKey, deeperMap);
        }

        recurseCreateMaps(deeperMap, key.substring(key.indexOf('.') + 1), value);
    } else {
        currentMap.put(key, value);
    }
}
0
répondu jgeerts 2017-08-07 09:49:13

Vous pouvez essayer avec https://github.com/mikolajmitura/java-properties-to-json

vous pouvez générer Json à partir de:

  • à partir de propriétés Java (java.util.Les propriétés)
  • à partir de la Carte (import java.util.Map) - > Map < String, String>
  • à partir de InputStream avec des propriétés (java.io.InputStream)
  • à partir d'un Fichier avec des propriétés (java.io.Fichier)
  • à partir d'une localisation de fichier donnée avec propriétés



ci-dessous variable "propriétés" doit être considéré comme l'un des types ci-dessus: java.util.Propriétés, Map, java.io.Entrants



exemple de code:

import pl.jalokim.propertiestojson.util.PropertiesToJsonConverter;

...

Properties properties = ....;
String jsonFromProperties = new PropertiesToJsonConverter().parseToJson(properties);

InputStream inputStream = ....;
String jsonFromInputStream = new PropertiesToJsonConverter().parseToJson(inputStream);

Map<String,String> mapProperties = ....;
String jsonFromInputProperties = new PropertiesToJsonConverter().parseToJson(mapProperties);

String jsonFromFilePath = new PropertiesToJsonConverter().parsePropertiesFromFileToJson("/home/user/file.properties");

String jsonFromFile = new PropertiesToJsonConverter().parsePropertiesFromFileToJson(new File("/home/user/file.properties"));

Maven dependency:

      <dependency>
          <groupId>pl.jalokim.propertiestojson</groupId>
          <artifactId>java-properties-to-json</artifactId>
          <version>3.1</version>
      </dependency>

dépendance requis java 7.

plus d'exemples d'utilisations sur https://github.com/mikolajmitura/java-properties-to-json

0
répondu Mikołaj Mitura 2018-07-03 08:18:01

Essayez de lire ce http://www.oracle.com/technetwork/articles/java/json-1973242.html, vous trouverez plusieurs classe pour travailler avec json.

je suppose que récupérer le json à partir d'un fichier local, une ressource interne dans le jar, ou à un autre endroit spécifié par une URL et le juste le lire avec un JsonReader obtenir les dones de travail.


ceci est un extrait du site de référence affiché avant.

 URL url = new URL("https://graph.facebook.com/search?q=java&type=post");
 try (InputStream is = url.openStream();
      JsonReader rdr = Json.createReader(is)) {

      JsonObject obj = rdr.readObject();
      // from this line forward you got what you want :D

     }
 }

j'Espère que ça aide!

-1
répondu Victor 2014-05-26 14:01:46