gson 下划线转驼峰
时间: 2023-09-29 08:08:37 浏览: 229
可以通过自定义 `JsonDeserializer` 来实现将下划线转换为驼峰的功能。以下是一个示例代码:
```java
import com.google.gson.*;
import java.lang.reflect.Type;
public class UnderlineToCamelDeserializer<T> implements JsonDeserializer<T> {
private static final String UNDERLINE = "_";
@Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
return new Gson().fromJson(underlineToCamel(jsonObject), typeOfT);
}
private JsonObject underlineToCamel(JsonObject jsonObject) {
JsonObject result = new JsonObject();
for (String key : jsonObject.keySet()) {
JsonElement value = jsonObject.get(key);
String camelKey = underlineToCamel(key);
if (value.isJsonObject()) {
result.add(camelKey, underlineToCamel(value.getAsJsonObject()));
} else if (value.isJsonArray()) {
result.add(camelKey, underlineToCamel(value.getAsJsonArray()));
} else {
result.add(camelKey, value);
}
}
return result;
}
private JsonArray underlineToCamel(JsonArray jsonArray) {
JsonArray result = new JsonArray();
for (JsonElement jsonElement : jsonArray) {
if (jsonElement.isJsonObject()) {
result.add(underlineToCamel(jsonElement.getAsJsonObject()));
} else if (jsonElement.isJsonArray()) {
result.add(underlineToCamel(jsonElement.getAsJsonArray()));
} else {
result.add(jsonElement);
}
}
return result;
}
private String underlineToCamel(String str) {
StringBuilder sb = new StringBuilder();
boolean flag = false;
for (char c : str.toCharArray()) {
if (c == '_') {
flag = true;
} else {
if (flag) {
sb.append(Character.toUpperCase(c));
flag = false;
} else {
sb.append(c);
}
}
}
return sb.toString();
}
}
```
然后在使用 `Gson` 解析 JSON 时,将自定义的 `JsonDeserializer` 传入即可:
```java
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyClass.class, new UnderlineToCamelDeserializer<>())
.create();
MyClass myClass = gson.fromJson(jsonString, MyClass.class);
```
阅读全文