日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

java json返回null_java-JSON jsonObject.optString()返回字符串“ null”

發布時間:2025/3/17 68 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java json返回null_java-JSON jsonObject.optString()返回字符串“ null” 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我的Josn解析器很長,必須創建一個新類來解決該問題,然后只需在每個方法中添加1條額外的行并重命名當前的JSONObject屬性名稱,因此所有其他調用都引用我的新類而不是JSONObject。

public static ArrayList readNews(String json) {

if (json != null) {

ArrayList res = new ArrayList<>();

try {

JSONArray jsonArray = new JSONArray(json);

for (int i = 0; i < jsonArray.length(); i++) {

//before JSONObject jo = jsonArray.getJSONObject(i);

JSONObject joClassic = jsonArray.getJSONObject(i);

//facade

FixJsonObject jo = new FixJsonObject(joClassic);

PieceOfNews pn = new PieceOfNews();

pn.setId(jo.getInt("id"));

pn.setImageUrl(jo.getString("imageURL"));

pn.setText(jo.getString("text"));

pn.setTitle(jo.getString("title"));

pn.setDate(jo.getLong("mills"));

res.add(pn);

}

return res;

} catch (JSONException e) {

e.printStackTrace();

}

}

return null;

}

這是我的類,其中包含我需要的方法,您可以添加更多

public class FixJsonObject {

private JSONObject jsonObject;

public FixJsonObject(JSONObject jsonObject) {

this.jsonObject = jsonObject;

}

public String optString(String key, String defaultValue) {

if (jsonObject.isNull(key)) {

return null;

} else {

return jsonObject.optString(key, defaultValue);

}

}

public String optString(String key) {

return optString(key, null);

}

public int optInt(String key) {

if (jsonObject.isNull(key)) {

return 0;

} else {

return jsonObject.optInt(key, 0);

}

}

public double optDouble(String key) {

return optDouble(key, 0);

}

public double optDouble(String key, double defaultValue) {

if (jsonObject.isNull(key)) {

return 0;

} else {

return jsonObject.optDouble(key, defaultValue);

}

}

public boolean optBoolean(String key, boolean defaultValue) {

if (jsonObject.isNull(key)) {

return false;

} else {

return jsonObject.optBoolean(key, defaultValue);

}

}

public long optLong(String key) {

if (jsonObject.isNull(key)) {

return 0;

} else {

return jsonObject.optLong(key, 0);

}

}

public long getLong(String key) {

return optLong(key);

}

public String getString(String key) {

return optString(key);

}

public int getInt(String key) {

return optInt(key);

}

public double getDouble(String key) {

return optDouble(key);

}

public JSONArray getJSONArray(String key) {

if (jsonObject.isNull(key)) {

return null;

} else {

return jsonObject.optJSONArray(key);

}

}

}

總結

以上是生活随笔為你收集整理的java json返回null_java-JSON jsonObject.optString()返回字符串“ null”的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。