我是Gson库的新手,我正在努力寻找一种合适的方法来使用Gson解析非常简单的json数据。下面是json示例:
{
"response": {
"status_code": "200",
"message": "User successfully registered.",
"response_for": "register"
}
}
我使用android捆绑的json.org库进行解析。
try {
JSONObject root = new JSONObject(json);
JSONObject response = root.getJSONObject("response");
int status = response.getInt("status_code");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
至于Gson,我遇到的问题是创建POJO类。我只对响应的status_code值感兴趣,因此创建pojo类是一种浪费。我试过的Gson样本如下:
JsonObject root = new Gson().fromJson(json, JsonObject.class);
Sring result = jobj.get("test").toString();
使用此代码,我只能解析非嵌套json
我只对响应的status_code值感兴趣创建pojo类是一种浪费。
那你为什么要用Gson呢?
引用gson文档"它可以用来将JSON字符串转换为等效的Java对象"
要获得status_code
,您的第一种方法应该有效。
public class Response {
Res response;
}
然后
public class Res {
public String status_code;
public String message;
public String response_for;
public Res(){}
}
然后InputStreamReader isr = new InputStreamReader (is);
Gson gson = new Gson();
Response lis = new Gson().fromJson(isr, Response.class);
Log.i("Response is ",""+lis.response.status_code);
Log.i("Message is ",""+lis.response.message);
Log.i("Response_for is ",""+lis.response.response_for);
日志06-13 17:55:52.126: I/Response is(8776): 200
06-13 17:55:52.126: I/Message is(8776): User successfully registered.
06-13 17:55:52.126: I/Response_for is(8776): register
后面的代码返回字符串值。
"status_code": "200",
"message": "User successfully registered.",
"response_for": "register"
你得到的是整数,我想你应该这样写,
JSONObject root = new JSONObject(json);
JSONObject response = root.getJSONObject("response");
int status = Integer.parseInt(response.getString("status_code"));