gpt4 book ai didi

android - 解析 json 时避免很多 try-catch 博客

转载 作者:太空狗 更新时间:2023-10-29 15:40:50 26 4
gpt4 key购买 nike

我尝试从 Facebook sdk 获取数据:

public void onCompleted(JSONObject object, GraphResponse response) {
String name = null;
try {
name = object.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
String profile = null;
try {
profile = object.getJSONObject("picture").getJSONObject("data").getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
String cover = null;
try {
cover = object.getJSONObject("cover").getString("source");
} catch (JSONException e) {
e.printStackTrace();
}
String email = null;
try {
email = object.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
String gender = null;
try {
gender = object.getString("gender");
} catch (JSONException e) {
e.printStackTrace();
}
String birthday = null;
try {
birthday = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
new SessionManager(activity).storeUserInfo(name, profile, cover, email, gender, birthday);
}

非常不利,因为字段很多,每个字段都可以为null,每个字段都需要一个try-cach blog。

我需要一个解决方案来更清晰地呈现代码。

最佳答案

如果只想去掉try catch block ,用“opt”代替“get”(例如。optInt(Key), optString(Key) ..)

请注意,如果键不存在,“opt”将返回null,它可能会在不检查的情况下引发许多空指针异常。

关于android - 解析 json 时避免很多 try-catch 博客,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34938640/

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