java属性为json
有没有一种简单的方法将带点符号的属性转换为json
IE
server.host=foo.bar server.port=1234
至
{ "server": { "host": "foo.bar", "port": 1234 } }
不是简单的方法,但我设法使用Gson
库。 结果将在jsonBundle
字符串中。 在这里我们获取这种情况下的属性或包:
final ResourceBundle bundle = ResourceBundle.getBundle("messages"); final Map bundleMap = resourceBundleToMap(bundle); final Type mapType = new TypeToken
对于此实现,必须将ResourceBundle
转换为包含String
作为键并将String
作为值的Map
。
private static Map resourceBundleToMap(final ResourceBundle bundle) { final Map bundleMap = new HashMap<>(); for (String key: bundle.keySet()) { final String value = bundle.getString(key); bundleMap.put(key, value); } return bundleMap; }
我必须使用Gson
为Map
创建自定义JSONSerializer
:
public class BundleMapSerializer implements JsonSerializer
这是创建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" } } }
希望这会有所帮助:)
这很简单,下载并添加到您的lib: https : //code.google.com/p/google-gson/
Gson gsonObj = new Gson(); String strJson = gsonObj.toJson(yourObject);
看看这个https://github.com/nzakas/props2js 。 您可以手动使用它,也可以在项目中使用它。
一点点递归和Gson 🙂
public void run() throws IOException { Properties properties = ...; Map map = new TreeMap<>(); for (Object key : properties.keySet()) { List keyList = Arrays.asList(((String) key).split("\\.")); Map 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 createTree(List keys, Map map) { Map valueMap = (Map) map.get(keys.get(0)); if (valueMap == null) { valueMap = new HashMap(); } map.put(keys.get(0), valueMap); Map out = valueMap; if (keys.size() > 2) { out = createTree(keys.subList(1, keys.size()), valueMap); } return out; }
我不想对gson有任何依赖,我想从Spring控制器返回一个层次结构json,所以深度Map对我来说已经足够了。
这对我有用,只需遍历所有键并传入空白地图。
void recurseCreateMaps(Map currentMap, String key, String value) { if (key.contains(".")) { String currentKey = key.split("\\.")[0]; Map deeperMap; if (currentMap.get(currentKey) instanceof Map) { deeperMap = (Map) currentMap.get(currentKey); } else { deeperMap = new HashMap<>(); currentMap.put(currentKey, deeperMap); } recurseCreateMaps(deeperMap, key.substring(key.indexOf('.') + 1), value); } else { currentMap.put(key, value); } }
您可以尝试使用https://github.com/mikolajmitura/java-properties-to-json
您可以从以下位置生成Json:
- 来自Java属性(java.util.Properties)
- 来自Map(import java.util.Map) – > Map
- 来自InputStream的属性(java.io.InputStream)
- 来自带有属性的文件(java.io.File)
- 从具有属性的给定文件本地化
下面的变量“properties”应该被认为是上述类型之一:java.util.Properties,Map
代码示例:
import pl.jalokim.propertiestojson.util.PropertiesToJsonConverter; ... Properties properties = ....; String jsonFromProperties = new PropertiesToJsonConverter().parseToJson(properties); InputStream inputStream = ....; String jsonFromInputStream = new PropertiesToJsonConverter().parseToJson(inputStream); Map 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依赖:
pl.jalokim.propertiestojson java-properties-to-json 3.1
依赖需要java 7。
更多https://github.com/mikolajmitura/java-properties-to-json上的使用示例
试试这个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 } }
希望能帮助到你!