我正在尝试将我的json字符串中的键转换为camelCase..我已经在堆栈溢出中找到了各种帖子,但无法找到解决方案..
我有一个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"
}
]
}
我已经写了一个jsonDeserializer类的基础上,在stackoverflow之前的帖子。
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;
}
当我使用上面的deserilizer时,虽然它能够将一些json数组对象的键转换为camle大小写......但我可以看到它只对每个数组中的一个jsonobject进行了转换,而没有将其他数组对象转换为consideration.as,如下所示。
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 serilization的新手,我无法再进步了...在这方面的任何帮助都非常感谢提前感谢
1条答案
按热度按时间5jvtdoz21#
您可以使用以下代码获取CamelCase字符串;
输出将为: