使用GSON处理随机生成和不一致的JSON字段/密钥名称

我有以下JSON代码段:

{ "randomlygeneratedKeyname0" : "some-value", "randomlygeneratedKeyname1": { "randomlygeneratedKeyname2" : { "randomlygeneratedKeyname3": "some-value", "randomlygeneratedKeyname4": "some-value" }, "randomlygeneratedKeyname5": { "randomlygeneratedKeyname6": "some-value", "randomlygeneratedKeyname7": "some-value" } } } 

请注意,我不知道randomgeneratedKeyname的名称及其命名约定是不一致的,因此我无法创建相应的Java字段/变量名称。

我如何(de)在GSON中序列化它?

在此先感谢您的帮助。

代码转储解决方案

 import java.io.FileReader; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; public class Foo { public static void main(String[] args) throws Exception { Type mapStringObjectType = new TypeToken>() {}.getType(); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(mapStringObjectType, new RandomMapKeysAdapter()); Gson gson = gsonBuilder.create(); Map map = gson.fromJson(new FileReader("input.json"), mapStringObjectType); System.out.println(map); } } class RandomMapKeysAdapter implements JsonDeserializer> { @Override public Map deserialize(JsonElement json, Type unused, JsonDeserializationContext context) throws JsonParseException { // if not handling primitives, nulls and arrays, then just if (!json.isJsonObject()) throw new JsonParseException("some meaningful message"); Map result = new HashMap (); JsonObject jsonObject = json.getAsJsonObject(); for (Entry entry : jsonObject.entrySet()) { String key = entry.getKey(); JsonElement element = entry.getValue(); if (element.isJsonPrimitive()) { result.put(key, element.getAsString()); } else if (element.isJsonObject()) { result.put(key, context.deserialize(element, unused)); } // if not handling nulls and arrays else { throw new JsonParseException("some meaningful message"); } } return result; } } 

我很高兴地报告, GSON 2.0不费吹灰之力就支持默认地图和列表。 像这样反序列化:

 Object o = new Gson().fromJson(json, Object.class); 

结果将是带有String键的Map以及StringMap值。

将该映射序列化为JSON,如下所示:

 String json = new Gson().toJson(o); 

我们希望在2012年10月发布GSON 2.0。您可以从GSON SVN早期获得它。