gpt4 book ai didi

android - 带有 Retrofit 转换器的 Gson 解串器 : just need inner JSON for all responses

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:28:31 25 4
gpt4 key购买 nike

我正在使用一个总是这样响应的 API:

{
"stuff_i_need": [
{
"title": "Hello"
},
{
"title": "World!"
}
],
"status": "success"
}

{
"other_things_key":
{
"version": "208"
},
"status": "success"
}

总是有两个元素,我只需要一个不是“身份”的元素。我也想用一个 GsonBuilder 来做到这一点。

我试过:

new GsonConverter(new GsonBuilder()
.registerTypeAdapter(List.class, new JsonDeserializer<List>() {
@Override
public List deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final JsonElement element = entry.getValue();
if (element.isJsonArray()) {
return new Gson().fromJson(element.getAsJsonArray(),
new TypeToken<List>(){}.getType());
}
}
return null;
}
)

但我认为那是不对的,它不满足更广泛的条件。

最佳答案

试试这个

public class ItemTypeAdapterFactory implements TypeAdapterFactory {

public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {

final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

return new TypeAdapter<T>() {

public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}

public T read(JsonReader in) throws IOException {

JsonElement jsonElement = elementAdapter.read(in);
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (jsonObject.has("data") && jsonObject.get("data").isJsonObject())
{
jsonElement = jsonObject.get("data");
}
}

return delegate.fromJsonTree(jsonElement);
}
}.nullSafe();
}}

接下来,您必须将它添加到 RestClient 中的 Gson 对象。

public class RestClient
{
private static final String BASE_URL = "your base url";
private ApiService apiService;

public RestClient()
{
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new ItemTypeAdapterFactory()) // This is the important line ;)
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.create();

RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(BASE_URL)
.setConverter(new GsonConverter(gson))
.setRequestInterceptor(new SessionRequestInterceptor())
.build();

apiService = restAdapter.create(ApiService.class);
}

public ApiService getApiService()
{
return apiService;
}
}

希望对你有帮助...

关于android - 带有 Retrofit 转换器的 Gson 解串器 : just need inner JSON for all responses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28601418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com