【问题标题】:java properties to jsonjson的java属性
【发布时间】:2014-05-26 13:50:01
【问题描述】:

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

I.E

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

到

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

【问题讨论】:

  • 在什么意义上你需要这个?您是否正在寻找用于在 Java 中创建/读取 json 的库? (例如查看库 GSON)
  • 我不明白为什么将这些人标记为否定,这只是一个问题。而不是标记否定,为什么你不首先考虑给出的答案?
  • 向我们展示您的尝试——只需大约 15 条直截了当的语句即可完成,而无需使用任何“聪明”的东西。
  • 致 Robadob:我想使用 freemarker 来评估模板文件。现在给定一个模板和一个 json freemarker 知道进行评估。问题是我的“密钥”以 java 属性文件格式存储。

标签: java json properties


【解决方案1】:

这不是简单的方法,但我设法使用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);

对于此实现,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;
}

我必须使用Gson 为Map&lt;String, String&gt; 创建自定义JSONSerializer:

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

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

最后,如果有一个键person.name.firstname的值为John,它会被转换成这样的JSON:

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

希望这会有所帮助:)

【讨论】:

  • 嗨,Yuriy,我使用了 Gjson2.3,并且在线程“main”java.lang.ClassCastException 中出现异常异常:com.google.gson.JsonPrimitive 无法转换为 com.google.gson。 JsonObject at com.google.gson.JsonObject.getAsJsonObject(JsonObject.java:182) at tools.BundleMapSerializer.getJsonIfExists(BundleMapSerializer.java:67)
  • 问题是properties中的对象不能同时是primitive和json对象,所以需要避免key重复如:key.name.a=something,key.name=某事2
  • 是的,你说得对,我发现了我的问题,就像你说的那样
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 结果是:{"server.host":"foo.bar","server.port":1234} 但我想创建一个分层的json
    【解决方案4】:

    我不希望对 gson 有任何依赖,我想从 Spring 控制器返回一个分层 json,因此深度 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);
        }
    }
    

    【讨论】:

      【解决方案5】:

      你可以试试https://github.com/mikolajmitura/java-properties-to-json

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

      • 来自 Java 属性 (java.util.Properties)
      • 从地图(导入 java.util.Map)-> 地图
      • 从地图(导入 java.util.Map)-> 地图
      • 来自带属性的 InputStream (java.io.InputStream)
      • 从给定的文件本地化和属性
      • 来自具有属性的文件 (java.io.File)


      代码示例:

      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>
                <groupId>pl.jalokim.propertiestojson</groupId>
                <artifactId>java-properties-to-json</artifactId>
                <version>5.1.0</version>
            </dependency>
      

      至少需要 java 8 的依赖项。

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

      【讨论】:

      • 在发布更多关于您的项目的信息之前,您可能需要阅读How to offer personal open-source libraries?。
      • Java 7 我真的需要这个!
      • 嗨 Martijn,只是想知道如何使用 PropertiesToJsonConverter().convertPropertiesFromFileToJson() 来保持属性文件元素的原始顺序?此方法始终按降序返回 JSON 内容。那可以配置吗?非常感谢!
      • @xman_bsn 这是不可配置的,“properties.load(inputStream);”丢失了真正的关键属性顺序在引擎盖下。但此时您可以执行以下 PropertyKeysOrderResolver 代码: PropertiesToJsonConverter converter = new PropertiesToJsonConverter(); converter.setPropertyKeysOrderResolver(new PropertyKeysOrderResolver() { public List getKeysInExpectedOrder(Map properties) { // TODO 实现方式你希望如何收集属性键顺序 } });
      • 从 5.1.3 版本开始,json 结构中的属性顺序与属性文件中的相同。从 Map 或 Properties 类直接转换属性的顺序将不会被保留。
      【解决方案6】:

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

      【讨论】:

      • 再次,这会将属性转换为平面 json,我正在寻找可以创建分层 json 的东西
      【解决方案7】:

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

      【讨论】:

        【解决方案8】:

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

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

        如果您还没有加载属性,您可以从文件中执行此操作

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

        如果你想反过来,将一个 json 字符串读入一个 prop 文件,你可以使用com.fasterxml.jackson.databind.ObjectMapper:

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

        【讨论】:

          【解决方案9】:

          我个人使用了这个依赖:

          <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-properties</artifactId> 
            <version>2.10.2</version>
            <scope>compile</scope>
          </dependency>
          
          private static JavaPropsMapper javaPropsMapper = JavaPropsMapper.builder().build();
          final JsonNode request = javaPropsMapper.readPropertiesAs(parameters, JsonNode.class);
          

          尝试使用架构验证来避免映射中可能出现的问题。

          虽然,使用简单的对象映射器也可以

          Properties properties = new Properties();
          properties.put("array", new int[] {1,2,3});
          ObjectMapper objectMapper = new ObjectMapper();
          objectMapper.writeValueAsString(parameters);
          

          输出

          {"fullname":["Foo","Bar"]}
          

          【讨论】:

            【解决方案10】:

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

            我猜想从本地文件、jar 中的内部资源或 URL 可指定的其他位置检索 json,然后使用 JsonReader 读取它即可完成工作。


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

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

            希望对你有帮助!

            【讨论】:

            • 这家伙需要将属性转换为 JSON。不仅仅是从文件中读取 json 到 JsonObject。
            猜你喜欢
            • 2016-06-04
            • 1970-01-01
            • 1970-01-01
            • 2017-12-24
            • 2018-06-15
            • 1970-01-01
            • 1970-01-01
            • 2020-08-26
            • 2020-02-20
            相关资源
            最近更新 更多