【发布时间】:2021-11-04 00:53:28
【问题描述】:
我正在尝试将我的 json 字符串中的键转换为 camelCase..我已经浏览了 stackoverflow 中的各种帖子,但无法找到解决方案..
我有一个以下格式的 json 字符串..
{
"tech":[
{
"id":"1",
"company_name":"Microsoft",
"country_of_origin":"USA"
},
{
"id":"2",
"company_name":"SAP",
"country_of_origin":"Germany"
}
],
"Manufacturing":[
{
"id":"3",
"company_name":"GM",
"country_of_origin":"USA"
},
{
"id":"4",
"company_name":"BMW",
"country_of_origin":"Germany"
}
]
}
预期响应
{
"tech":[
{
"id":"1",
"companyName":"Microsoft",
"countryOfOrigin":"USA"
},
{
"id":"2",
"companyName":"SAP",
"countryOfOrigin":"Germany"
}
],
"Manufacturing":[
{
"id":"3",
"companyName":"GM",
"countryOfOrigin":"USA"
},
{
"id":"4",
"companyName":"BMW",
"countryOfOrigin":"Germany"
}
]
}
我已经根据 stackoverflow 中的上一篇文章编写了一个 jsonDeserializer 类..
Gson gson = new GsonBuilder()
.registerTypeAdapter(UpperCaseAdapter.TYPE, new UpperCaseAdapter())
.create();
Map<String, List<Company>> mapDeserialized = gson.fromJson(jsonString, UpperCaseAdapter.TYPE);
System.out.println(mapDeserialized);
还有脱硫剂
public class UpperCaseAdapter implements JsonDeserializer<Map<String, Object>> {
public static final Type TYPE = new TypeToken<Map<String, Object>>() {}.getType();
@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);
} else if (entry.getValue().isJsonArray()) {
for(JsonElement jsonElement:entry.getValue().getAsJsonArray()){
value=context.deserialize(jsonElement,TYPE);
}
} else if (entry.getValue().isJsonNull()) {
continue;
}
map.put(CaseFormat.LOWER_UNDERSCORE.to(
CaseFormat.LOWER_CAMEL, entry.getKey()), value);
}
return map;
}
}
模型类
public class Company {
private String id;
private String compnayName;
private String countryOfOrigin;
}
当我使用上述解串器时,虽然它能够将某些 json 数组对象的键转换为 camle 大小写....我可以看到它只对每个数组中的一个 jsonobject 执行此操作,而不采用其他数组对象在考虑中。如下图。
Wrong Response i am getting with above serializer(missing other jsonobjecsts and the key manufacturing is converted to lower):
{
"tech="{
"companyName=SAP",
id=2,
"countryOfOrigin=Germany"
},
"manufacturing="{
"companyName=BMW",
id=4,
"countryOfOrigin=Germany"
}
}
我知道 stackoverflow 中有很多可用的帖子,我只能基于这些帖子,但由于我是 Java 和 json 序列化的新手,我无法再进步......这方面的任何帮助都很大提前感谢感谢
【问题讨论】:
-
嗨,非常感谢您的帮助??
标签: java arrays json gson jsonserializer