Android 将Facebook JSON响应映射到POJO
我正在对Facebook进行API调用,并收到以下Json对象:Android 将Facebook JSON响应映射到POJO,android,json,gson,Android,Json,Gson,我正在对Facebook进行API调用,并收到以下Json对象: {"first_name":"FirstName", "last_name":"LastName", "email":"email@email.com", "picture":{"data":{"is_silhouette":true,"url":"pictureUrl"}},"id":"12345"} 我目前没有手动反序列化对象,而是对其使用Gson,如下所示: FacebookProfileModel facebookPro
{"first_name":"FirstName",
"last_name":"LastName",
"email":"email@email.com",
"picture":{"data":{"is_silhouette":true,"url":"pictureUrl"}},"id":"12345"}
我目前没有手动反序列化对象,而是对其使用Gson
,如下所示:
FacebookProfileModel facebookProfileModel = new Gson().fromJson(object.toString(), FacebookProfileModel.class);
下面是我的POJO的样子:
@SerializedName("first_name")
String mFirstName;
@SerializedName("last_name")
String mLastName;
@SerializedName("email")
String mEmail;
@SerializedName("url")
String mUrl;
显然,我正在接收除url之外的所有值,因为该值位于两个Json对象中:
picture
和data
。我想一个可能的解决方案(但不是最好的)是在Facebook模型中创建图片
对象,然后在图片
对象中创建数据
对象,但是为一个字符串再创建两个POJO感觉很糟糕。还有其他解决方案吗?没有基于注释的解决方案。但是,自定义反序列化程序可以解决此问题
自定义反序列化程序:-
public class FacebookProfileModelDeserializer implements JsonDeserializer<FacebookProfileModel> {
@Override
public FacebookProfileModel deserialize(JsonElement paramJsonElement, Type paramType,
JsonDeserializationContext paramJsonDeserializationContext) throws JsonParseException {
String url = paramJsonElement.getAsJsonObject().get("picture").getAsJsonObject().get("data").getAsJsonObject()
.get("url").getAsString();
FacebookProfileModel facebookProfileModel = new Gson().fromJson(paramJsonElement.getAsJsonObject(),
FacebookProfileModel.class);
facebookProfileModel.setmUrl(url);
return facebookProfileModel;
}
}
public static void main(String[] args) {
String jsonString = "{\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"email\":\"email@email.com\",\"picture\":{\"data\":{\"is_silhouette\":true,\"url\":\"pictureUrl\"}},\"id\":\"12345\"}";
Gson gson = new GsonBuilder()
.registerTypeAdapter(FacebookProfileModel.class, new FacebookProfileModelDeserializer())
.create();
FacebookProfileModel faceBookProfileModel = gson.fromJson(jsonString, FacebookProfileModel.class);
System.out.println(faceBookProfileModel.toString());
}
谢谢分享。这确实是一个很好的解决方案,我目前正在使用它来处理类似的事情,我最终创建了2个POJO,因为由于更多的功能,我可能会在某个时候扩展POJO。我将接受并投票赞成这个解决方案,因为它是一个好的解决方案。