java 属性到 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23871694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:45:27  来源:igfitidea点击:

java properties to json

javajsonproperties

提问by Vitali Bichov

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

有没有一种简单的方法可以将带有点符号的属性转换为 json

I.E

IE

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

TO

{
 "server": {
    "host": "foo.bar",
    "port": 1234
  }
} 

回答by klapvee

It is pretty easy, download and add to your lib: https://code.google.com/p/google-gson/

这很容易,下载并添加到您的库中:https: //code.google.com/p/google-gson/

Gson gsonObj = new Gson();
String strJson =  gsonObj.toJson(yourObject);

回答by Victor

Try reading this http://www.oracle.com/technetwork/articles/java/json-1973242.html, you will find several class to work with json.

尝试阅读这个http://www.oracle.com/technetwork/articles/java/json-1973242.html,你会发现几个类可以使用 json。

I guess that retrieving the json from a local file, inner resource in the jar, or in another location specificable by an URL and the just read it with a JsonReader get the job dones.

我想从本地文件、jar 中的内部资源或在 URL 指定的另一个位置检索 json 并使用 JsonReader 读取它就可以完成工作。



This is a snipped from the reference site posted before.

这是从之前发布的参考站点中截取的。

 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

     }
 }

Hope it helps!

希望能帮助到你!

回答by Ostap Maliuvanchuk

Look at this https://github.com/nzakas/props2js. You can use it manually or fork and use in your project.

看看这个https://github.com/nzakas/props2js。您可以手动使用它或在您的项目中 fork 和使用它。

回答by Yuriy Yunikov

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

不是简单的方法,但我设法使用Gson库来做到这一点。结果将在 jsonBundle字符串中。在这种情况下,我们在这里获取属性或包:

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 ResourceBundlehave to be converted to Mapcontaining Stringas a key and Stringas a value.

对于此实现ResourceBundle,必须转换为Map包含String作为键和String作为值。

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 JSONSerializerusing Gsonfor Map<String, String>:

我必须JSONSerializer使用Gsonfor创建自定义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:

这是创建 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();
        }
   }

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

最后,如果有一个person.name.firstname带有 value的键John,它将被转换为这样的JSON

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

Hope this will help :)

希望这会有所帮助:)

回答by Mark

A little bit recursion and Gson :)

一点点递归和 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;
}

回答by Miko?aj Mitura

You can try with https://github.com/mikolajmitura/java-properties-to-json

您可以尝试使用https://github.com/mikolajmitura/java-properties-to-json

You can generate Json from:

您可以从以下位置生成 Json:

  • from Java properties (java.util.Properties)
  • from Map (import java.util.Map) -> Map<String,String>
  • from Map (import java.util.Map) -> Map<String,Object>
  • from InputStream with properties (java.io.InputStream)
  • from given file localization with properties
  • from File with properties (java.io.File)
  • 从 Java 属性 (java.util.Properties)
  • from Map (import java.util.Map) -> Map<String,String>
  • from Map (import java.util.Map) -> Map<String,Object>
  • 来自具有属性的 InputStream (java.io.InputStream)
  • 从具有属性的给定文件本地化
  • 来自带有属性的文件 (java.io.File)


code example:


代码示例:

import pl.jalokim.propertiestojson.util.PropertiesToJsonConverter;

...

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

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

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

Map<String, Object> valuesAsObjectMap = ....;
String jsonFromProperties2 = new PropertiesToJsonConverter().convertFromValuesAsObjectMap(valuesAsObjectMap);

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

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

maven dependency:

Maven 依赖:

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

dependency required minimum java 8.

依赖要求最低java 8。

more example of uses on https://github.com/mikolajmitura/java-properties-to-json

https://github.com/mikolajmitura/java-properties-to-json上的更多使用示例

回答by jgeerts

I didn't want any dependency on gson and I wanted to return a hierarchical json from a Spring controller so a deep Map was enough for me.

我不想对 gson 有任何依赖,我想从 Spring 控制器返回一个分层的 json,所以一个深 Map 对我来说就足够了。

This works for me, just loop over all your keys and pass in an empty map.

这对我有用,只需遍历所有键并传入一个空地图。

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

回答by StevenWernerCS

just use org.json.JSONObjectconstructor that receives a Map (which Properties extends):

只需使用org.json.JSONObject接收 Map (其 Properties 扩展)的构造函数:

JSONObject jsonProps = new JSONObject(properties);
jsonProps.toString();

If you don't already have the properties loaded you can do that from a file

如果您还没有加载属性,您可以从文件中加载

Properties properties= new Properties();
File file = new File("/path/to/test.properties");
FileInputStream fileInput = new FileInputStream(file);
properties.load(fileInput);

If you want to do the reverse, and read a json string into a prop file you can use com.fasterxml.Hymanson.databind.ObjectMapper:

如果你想做相反的事情,并将一个 json 字符串读入一个 prop 文件,你可以使用com.fasterxml.Hymanson.databind.ObjectMapper

HashMap<String,String> result = new ObjectMapper().readValue(jsonPropString, HashMap.class);
Properties props = new Properties();
props.putAll(result);

回答by raisercostin

Using lightbend config java library (https://github.com/lightbend/config)

使用 lightbend 配置 java 库 ( https://github.com/lightbend/config)

String toHierarchicalJsonString(Properties props) {
  com.typesafe.config.Config config = com.typesafe.config.ConfigFactory.parseProperties(props);
  return config.root().render(com.typesafe.config.ConfigRenderOptions.concise());
}