[英]How do I parse a field from a deep nested json object using Gson and retrofit in android?
[英]Get nested JSON object with GSON using retrofit
我正在从我的 android 应用程序中使用一个 API,所有的 JSON 响应都是这样的:
{
'status': 'OK',
'reason': 'Everything was fine',
'content': {
< some data here >
}
问题是我所有的 POJO 都有一个status
, reason
字段,并且content
字段里面是我想要的真正的 POJO。
有没有办法创建一个自定义的 Gson 转换器来始终提取content
字段,以便改造返回适当的 POJO?
您将编写一个返回嵌入对象的自定义反序列化器。
假设您的 JSON 是:
{
"status":"OK",
"reason":"some reason",
"content" :
{
"foo": 123,
"bar": "some value"
}
}
然后,您将拥有一个Content
POJO:
class Content
{
public int foo;
public String bar;
}
然后你写一个反序列化器:
class MyDeserializer implements JsonDeserializer<Content>
{
@Override
public Content deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException
{
// Get the "content" element from the parsed JSON
JsonElement content = je.getAsJsonObject().get("content");
// Deserialize it. You use a new instance of Gson to avoid infinite recursion
// to this deserializer
return new Gson().fromJson(content, Content.class);
}
}
现在,如果您使用GsonBuilder
构建Gson
并注册反序列化器:
Gson gson =
new GsonBuilder()
.registerTypeAdapter(Content.class, new MyDeserializer())
.create();
您可以将 JSON 直接反序列化为Content
:
Content c = gson.fromJson(myJson, Content.class);
编辑以从评论中添加:
如果您有不同类型的消息,但它们都有“内容”字段,您可以通过执行以下操作使反序列化器通用:
class MyDeserializer<T> implements JsonDeserializer<T>
{
@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException
{
// Get the "content" element from the parsed JSON
JsonElement content = je.getAsJsonObject().get("content");
// Deserialize it. You use a new instance of Gson to avoid infinite recursion
// to this deserializer
return new Gson().fromJson(content, type);
}
}
您只需要为每种类型注册一个实例:
Gson gson =
new GsonBuilder()
.registerTypeAdapter(Content.class, new MyDeserializer<Content>())
.registerTypeAdapter(DiffContent.class, new MyDeserializer<DiffContent>())
.create();
当您调用.fromJson()
该类型被带入反序列化器,因此它应该适用于您的所有类型。
最后在创建 Retrofit 实例时:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
@BrianRoach 的解决方案是正确的解决方案。 值得注意的是,在嵌套的自定义对象都需要自定义TypeAdapter
的特殊情况下,您必须将TypeAdapter
注册到TypeAdapter
的新实例,否则将永远不会调用第二个TypeAdapter
。 这是因为我们正在自定义反序列化器中创建一个新的Gson
实例。
例如,如果您有以下 json:
{
"status": "OK",
"reason": "some reason",
"content": {
"foo": 123,
"bar": "some value",
"subcontent": {
"useless": "field",
"data": {
"baz": "values"
}
}
}
}
您希望将此 JSON 映射到以下对象:
class MainContent
{
public int foo;
public String bar;
public SubContent subcontent;
}
class SubContent
{
public String baz;
}
您需要注册SubContent
的TypeAdapter
。 为了更健壮,您可以执行以下操作:
public class MyDeserializer<T> implements JsonDeserializer<T> {
private final Class mNestedClazz;
private final Object mNestedDeserializer;
public MyDeserializer(Class nestedClazz, Object nestedDeserializer) {
mNestedClazz = nestedClazz;
mNestedDeserializer = nestedDeserializer;
}
@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
// Get the "content" element from the parsed JSON
JsonElement content = je.getAsJsonObject().get("content");
// Deserialize it. You use a new instance of Gson to avoid infinite recursion
// to this deserializer
GsonBuilder builder = new GsonBuilder();
if (mNestedClazz != null && mNestedDeserializer != null) {
builder.registerTypeAdapter(mNestedClazz, mNestedDeserializer);
}
return builder.create().fromJson(content, type);
}
}
然后像这样创建它:
MyDeserializer<Content> myDeserializer = new MyDeserializer<Content>(SubContent.class,
new SubContentDeserializer());
Gson gson = new GsonBuilder().registerTypeAdapter(Content.class, myDeserializer).create();
这也可以很容易地用于嵌套的“内容”情况,只需传入一个具有空值的MyDeserializer
的新实例。
有点晚了,但希望这会对某人有所帮助。
只需创建以下 TypeAdapterFactory。
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("content")) {
jsonElement = jsonObject.get("content");
}
}
return delegate.fromJsonTree(jsonElement);
}
}.nullSafe();
}
}
并将其添加到您的 GSON 构建器中:
.registerTypeAdapterFactory(new ItemTypeAdapterFactory());
或者
yourGsonBuilder.registerTypeAdapterFactory(new ItemTypeAdapterFactory());
前几天遇到同样的问题。 我已经使用响应包装器类和 RxJava 转换器解决了这个问题,我认为这是非常灵活的解决方案:
包装:
public class ApiResponse<T> {
public String status;
public String reason;
public T content;
}
自定义异常抛出,当状态不正常时:
public class ApiException extends RuntimeException {
private final String reason;
public ApiException(String reason) {
this.reason = reason;
}
public String getReason() {
return apiError;
}
}
接收变压器:
protected <T> Observable.Transformer<ApiResponse<T>, T> applySchedulersAndExtractData() {
return observable -> observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map(tApiResponse -> {
if (!tApiResponse.status.equals("OK"))
throw new ApiException(tApiResponse.reason);
else
return tApiResponse.content;
});
}
用法示例:
// Call definition:
@GET("/api/getMyPojo")
Observable<ApiResponse<MyPojo>> getConfig();
// Call invoke:
webservice.getMyPojo()
.compose(applySchedulersAndExtractData())
.subscribe(this::handleSuccess, this::handleError);
private void handleSuccess(MyPojo mypojo) {
// handle success
}
private void handleError(Throwable t) {
getView().showSnackbar( ((ApiException) throwable).getReason() );
}
继续 Brian 的想法,因为我们几乎总是有许多 REST 资源,每个资源都有自己的根,因此概括反序列化可能很有用:
class RestDeserializer<T> implements JsonDeserializer<T> {
private Class<T> mClass;
private String mKey;
public RestDeserializer(Class<T> targetClass, String key) {
mClass = targetClass;
mKey = key;
}
@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException {
JsonElement content = je.getAsJsonObject().get(mKey);
return new Gson().fromJson(content, mClass);
}
}
然后从上面解析示例有效负载,我们可以注册 GSON 反序列化器:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Content.class, new RestDeserializer<>(Content.class, "content"))
.build();
更好的解决方案可能是这样..
public class ApiResponse<T> {
public T data;
public String status;
public String reason;
}
然后,像这样定义您的服务..
Observable<ApiResponse<YourClass>> updateDevice(..);
根据@Brian Roach 和@rafakob 的回答,我是通过以下方式完成的
来自服务器的 Json 响应
{
"status": true,
"code": 200,
"message": "Success",
"data": {
"fullname": "Rohan",
"role": 1
}
}
通用数据处理程序类
public class ApiResponse<T> {
@SerializedName("status")
public boolean status;
@SerializedName("code")
public int code;
@SerializedName("message")
public String reason;
@SerializedName("data")
public T content;
}
自定义序列化程序
static class MyDeserializer<T> implements JsonDeserializer<T>
{
@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException
{
JsonElement content = je.getAsJsonObject();
// Deserialize it. You use a new instance of Gson to avoid infinite recursion
// to this deserializer
return new Gson().fromJson(content, type);
}
}
Gson 对象
Gson gson = new GsonBuilder()
.registerTypeAdapter(ApiResponse.class, new MyDeserializer<ApiResponse>())
.create();
api调用
@FormUrlEncoded
@POST("/loginUser")
Observable<ApiResponse<Profile>> signIn(@Field("email") String username, @Field("password") String password);
restService.signIn(username, password)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<ApiResponse<Profile>>() {
@Override
public void onCompleted() {
Log.i("login", "On complete");
}
@Override
public void onError(Throwable e) {
Log.i("login", e.toString());
}
@Override
public void onNext(ApiResponse<Profile> response) {
Profile profile= response.content;
Log.i("login", profile.getFullname());
}
});
这与@AYarulin 的解决方案相同,但假设类名是 JSON 键名。 这样你只需要传递类名。
class RestDeserializer<T> implements JsonDeserializer<T> {
private Class<T> mClass;
private String mKey;
public RestDeserializer(Class<T> targetClass) {
mClass = targetClass;
mKey = mClass.getSimpleName();
}
@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException {
JsonElement content = je.getAsJsonObject().get(mKey);
return new Gson().fromJson(content, mClass);
}
}
然后从上面解析示例有效负载,我们可以注册 GSON 解串器。 这是有问题的,因为 Key 区分大小写,因此类名的大小写必须与 JSON 键的大小写匹配。
Gson gson = new GsonBuilder()
.registerTypeAdapter(Content.class, new RestDeserializer<>(Content.class))
.build();
这是基于 Brian Roach 和 AYarulin 的答案的 Kotlin 版本。
class RestDeserializer<T>(targetClass: Class<T>, key: String?) : JsonDeserializer<T> {
val targetClass = targetClass
val key = key
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): T {
val data = json!!.asJsonObject.get(key ?: "")
return Gson().fromJson(data, targetClass)
}
}
就我而言,每个响应的“内容”键都会改变。 例子:
// Root is hotel
{
status : "ok",
statusCode : 200,
hotels : [{
name : "Taj Palace",
location : {
lat : 12
lng : 77
}
}, {
name : "Plaza",
location : {
lat : 12
lng : 77
}
}]
}
//Root is city
{
status : "ok",
statusCode : 200,
city : {
name : "Vegas",
location : {
lat : 12
lng : 77
}
}
在这种情况下,我使用了上面列出的类似解决方案,但不得不对其进行调整。 你可以在这里看到要点。 把它张贴在 SOF 上有点太大了。
使用注解@InnerKey("content")
,其余的代码是为了方便它与 Gson 的使用。
不要忘记@SerializedName
从 JSON 反序列化的所有类成员和内部类成员的@SerializedName
和@Expose
注释。
另一个简单的解决方案:
JsonObject parsed = (JsonObject) new JsonParser().parse(jsonString);
Content content = gson.fromJson(parsed.get("content"), Content.class);
有一种更简单的方法,只需将content
子对象视为另一个类:
class Content {
var foo = 0
var bar: String? = null
}
class Response {
var statis: String? = null
var reason: String? = null
var content: Content? = null
}
现在您可以使用Response
类型来反序列化 json。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.