如果属性文件包含以下类型值,如何将其直接读入地图
Use Managed Compatibility Mode
提前谢谢!
答案 0 :(得分:5)
您可以使用@Value
注释从属性文件将值注入Map中。
@Value("#{${user}}")
private Map<String, String> user;
您的application.properties中的条目必须为:
user = {"name":"test","age":"23","place":"London"}
答案 1 :(得分:1)
test.properties文件
name=test
age=23
place=london
代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
public class ReadPropertiesFile {
public static void main(String[] args) {
try {
File file = new File("test.properties");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
fileInput.close();
Enumeration enuKeys = properties.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);
System.out.println(key + ": " + value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
希望,这会有所帮助..:)
答案 2 :(得分:1)
这将读取属性文件并将其放入Properties
对象中。
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesConfig {
private Properties prop;
private PropertiesConfig() {
super();
init();
}
private static class PropertiesInstance {
private static PropertiesConfig instance = null;
public static PropertiesConfig getInstance() {
if (null == instance) {
instance = new PropertiesConfig();
}
return instance;
}
}
public static PropertiesConfig getInstance() {
return PropertiesInstance.getInstance();
}
private void init() {
prop = new Properties();
try (InputStream input = getClass().getResourceAsStream("/sample_config.properties")) {
// load a properties file
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public String getProperty(String key) {
return prop.getProperty(key);
}
}
现在,您可以使用任何库将值转换为Map,因为您的值看起来像JSON。
通过杰克逊实现此目的的代码示例:
public static Map < String, Object > covertFromJsonToMap(String json) throws JsonTransformException {
try {
return mapper.readValue(json, new TypeReference < HashMap < String, Object >> () {});
} catch (Exception e) {
LOGGER.error("Error " + json, e);
throw new JsonTransformException("Error in json parse", e);
}
}
所以这样的事情会做:
covertFromJsonToMap(PropertiesConfig.getInstance().get("user"));
答案 3 :(得分:0)
好像您将地图的JSON表示形式作为值。在Java中以字符串形式读取值后,就可以使用Gson将其转换为地图
Gson gson = new Gson();
String json = <YOUR_STRING>
Map<String,Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(json, map.getClass());