将嵌套的JSON密钥转换为大写

时间:2019-03-23 09:54:51

标签: java json gson

我想将JSON字符串/对象的所有键转换为Java中的大写。可以嵌套JSON。

我尝试在GsonBuilder中设置FieldNamingPolicy.UPPER_CAMEL_CASE,但我想这仅适用于将String转换为JAVA对象,而不适用于将String转换为String。

 String payload = "{\"key\" : {\"key1\" : \"value1\",\"key2\" : \"value2\"}}";
 GsonBuilder gsonBuilder = new GsonBuilder();
 gsonBuilder.registerTypeAdapterFactory(myCustomTypeAdapterFactory);
 gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
 Gson gson = gsonBuilder.create();
 Map mapDeserialized = gson.fromJson(payload, Map.class);

 System.out.println("Map " + mapDeserialized);

JACKSON还有其他带有自定义TypeAdapterFactory的解决方案,但这些解决方案仅适用于一个级别,不适用于嵌套。

{"key" : { "key1" : "value1", "key2" : "value2" }}

{"KEY" : { "KEY1" : "value1", "KEY2" : "value2" }}

1 个答案:

答案 0 :(得分:1)

正如您所说,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}}