正如您所说,FieldNamingPolicy 仅适用于 bean 字段而不适用于映射键。但是 UPPER_CAMEL_CASE 不是您想要的,它是首字母大写的驼峰式大小写(SometingLikeThis)。你必须实现你自己的反序列化器来为你做到这一点:
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class UpperCaseAdapter implements JsonSerializer<Map<String, Object>>, JsonDeserializer<Map<String, Object>> {
public static final Type TYPE = new TypeToken<Map<String, Object>>() {}.getType();
@Override
public JsonElement serialize(Map<String, Object> src, Type typeOfSrc, JsonSerializationContext context) {
// TODO implement serialization if needed
return null;
}
@Override
public Map<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Map<String, Object> map = new HashMap<>();
for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
Object value = null;
if (entry.getValue().isJsonPrimitive()) {
value = entry.getValue().getAsString();
} else if (entry.getValue().isJsonObject()) {
value = context.deserialize(entry.getValue(), TYPE); // deserialize the object using the same type
} else if (entry.getValue().isJsonArray()) {
// TODO implement deserailization of array
} else if (entry.getValue().isJsonNull()) {
// skip nulls
continue;
}
map.put(entry.getKey().toUpperCase(), value); //toUpperCase() is what we want
}
return map;
}
}
然后您可以使用适配器:
String payload = "{\"key\" : {\"key1\" : \"value1\",\"key2\" : \"value2\"}, \"key3\": \"value\"}";
Gson gson = new GsonBuilder()
.registerTypeAdapter(UpperCaseAdapter.TYPE, new UpperCaseAdapter())
.create();
Map<String, Object> mapDeserialized = gson.fromJson(payload, UpperCaseAdapter.TYPE);
System.out.println("Map " + mapDeserialized);
输出是:
Map {KEY3=value, KEY={KEY2=value2, KEY1=value1}}