将嵌套的JSON密钥转换为UPPERCASE

问题描述 投票:0回答:1

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

我尝试在GsonBuilder中设置FieldNamingPolicy.UPPER_CAMEL_CASE,但我想这只适用于String到JAVA Object而不适用于String to 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" }}

java json gson
1个回答
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}}

© www.soinside.com 2019 - 2024. All rights reserved.