簡體   English   中英

解析時JSON對象為null

[英]JSON Object is null while parsing

我的json對象的格式為:

   String jsonObjRecv =  {
      "response":{
       "respobj":{
        "id":<int>,
        "number":<string>,
        "validated":<boolean>
         }
        },
        "status":"ok",
        "errors":null
        }

當代碼為:

        JSONObject jsonObjCont = new JSONObject(jsonObjRecv);
        String getString= jsonObjCont.toString(2);

在這種情況下,getString!= null可以接收數據,但是當我嘗試獲取JSON對象的嵌套數據時,如下所示:

        JSONObject jsonObjCont = new JSONObject(jsonObjRecv);
        JSONObject regNumber = jsonObjCont.getJSONObject("respobj");
        String number= regNumber.getString("number");

它不起作用。

我嘗試使用GSON庫,但在以下情況下可以使用:

public String parse(String jsonObjRecv) {
    JsonElement jelement = new JsonParser().parse(jsonObjRecv);
    String result = jelement.toString();
    return result;

而且不起作用:

public String parse(String jsonObjRecv) {
    JsonElement jelement = new JsonParser().parse(jsonObjRecv);
    JsonObject jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("respobj");

    String result = jobject.get("number").toString();
    return result;

我的錯誤在哪里?

問題是您無法正確訪問JSON對象-這是一個包含response對象的對象,該response對象包含respobj對象。

Gson示例如下。 注意代碼中的注釋-您需要獲取response對象, 然后從中獲取respobj

public static void main( String[] args )
{
    String jsonObjRecv =  "{\"response\":{\"respobj\":{\"id\":1,\"number\":\"22\",\"validated\":true}},\"status\":\"ok\",\"errors\":null}";

    JsonElement jelement = new JsonParser().parse(jsonObjRecv);
    JsonObject jobject = jelement.getAsJsonObject();

    // Here is where you're making an error. You need to get the outer
    // 'response' object first, then get 'respobj' from that.
    jobject = jobject.getAsJsonObject("response").getAsJsonObject("respobj");

    String result = jobject.get("number").getAsString();

    System.out.println(result);

}

輸出:

22

編輯添加:注意,我使用了getAsString()toString() -如果使用后者,則會得到原始的JSON,它將在值周圍包含引號(例如,輸出為"22"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM