使用GSON解析json响应的正确方法是什么?Json解析两次或每次创建响应类?

时间:2022-07-23 19:35:35

I want to know in a scenario where server json response is in the below format

我想知道在一个场景中,服务器json响应的格式如下。

{
 "data": {
    "id": 1948,
    "body": "test comment",
    "created_at": "2014-06-24T16:05:31+00:00",
    "user_id": 2963,
    ...
}
}

in Json parsing using GSON, whether it is right to parse

在使用GSON的Json解析中,解析是否正确。

JSONObject jsonObject = new JSONObject(json);
String jsonData = jsonObject.getString("data");
return Response.success(mGson.fromJson(json,mClazz),HttpHeaderParser.parseCacheHeaders(response));

or to just return

或只返回

Response.success(mGson.fromJson(json,mClazz),HttpHeaderParser.parseCacheHeaders(response)); and create a response class for every server api call like

mClazz Response.success(mGson.fromJson(json),HttpHeaderParser.parseCacheHeaders(响应));并为每个服务器api调用创建一个响应类。

public class CommentsResponse {  
 private Comment data;
 ..
}

1 个解决方案

#1


0  

The first case might be better because it tells if you if the response was a valid JSONObject or not when you convert the reponse to JSONObject and you might wanna handle that case since an exception will be thrown if its not.

第一个例子可能会更好,因为它告诉你,如果响应是一个有效的JSONObject,或者当你将reponse转换为JSONObject时,你可能想要处理这种情况,因为如果不是,就会抛出一个异常。

#1


0  

The first case might be better because it tells if you if the response was a valid JSONObject or not when you convert the reponse to JSONObject and you might wanna handle that case since an exception will be thrown if its not.

第一个例子可能会更好,因为它告诉你,如果响应是一个有效的JSONObject,或者当你将reponse转换为JSONObject时,你可能想要处理这种情况,因为如果不是,就会抛出一个异常。