2016-03-29 15 views
2

私は、サーバーからデータを取得するのにvolley + OkHttpを使用しています。GSON/POJOでJSONを解析する

レスポンスは、GSON/POJOを使用して解析するJSONを含む文字列です。

Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

解析しよう:

私はエラーを取得します。

Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:388)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:209)
at com.google.gson.Gson.fromJson(Gson.java:879) 
at com.google.gson.Gson.fromJson(Gson.java:844) 
at com.google.gson.Gson.fromJson(Gson.java:793) 
at com.google.gson.Gson.fromJson(Gson.java:765) 
at test.com.example.buddy.myapplication.MainActivity$8.onResponse(MainActivity.java:192) //

ライン192は、私が期待どおりに動作しますJSON_STRINGの下に使用一方Post component = gson.fromJson(response, Post.class);

であり、私はPOJOクラスを使用して値を取得します。

String JSON_STRING = "{\"currentBalance\":{\"amount\":0.0,\"currencyCode\":\"EUR\"},\"currentBalanceDisplay\":true,\"overdueAmount\":null,\"overdueAmountDisplay\":false," + 
        "\"creditAmount\":null,\"creditAmountDisplay\":false,\"noOfBillsToShow\":3,\"recentBills\":[{\"period\":\"03 2016\",\"amount\":{\"amount\":22.76," + 
        "\"currencyCode\":\"EUR\"},\"status\":\"PAID\",\"dueDate\":\"14-03-2016\",\"sortOrder\":\"20160308\",\"periodType\":\"MONTHLY\"," + 
        "\"invoiceId\":\"277726719\",\"invoiceDate\":\"08-03-2016\"}]}"; 

誰かが助けてくれたら嬉しいです。前もって感謝します。

EDIT:予想通り私は完全な馬鹿のように感じる:)それは私が間違ったURLを照会して判明、すべてが動作します。私を助けてくれてありがとう、もう一度ありがとう。サーバーから

文字列の応答:

{ 
    "currentBalance": { 
    "amount": 0.0, 
    "currencyCode": "EUR" 
    }, 
    "currentBalanceDisplay": true, 
    "overdueAmount": null, 
    "overdueAmountDisplay": false, 
    "creditAmount": null, 
    "creditAmountDisplay": false, 
    "noOfBillsToShow": 3, 
    "recentBills": [ 
    { 
     "period": "03 2016", 
     "amount": { 
     "amount": 12.53, 
     "currencyCode": "EUR" 
     }, 
     "status": "PAID", 
     "dueDate": "14-03-2016", 
     "sortOrder": "2548264", 
     "periodType": "MONTHLY", 
     "invoiceId": "", 
     "invoiceDate": "08-03-2016" 
    } 
    ] 
} 

ボレー要求:

private void FetchData() { 

StringRequest finalrequest = new StringRequest(Request.Method.POST, FETCHURL, 
     new Response.Listener<String>() { 

      @Override 
      public void onResponse(String response) { 

       Gson gson = new Gson(); 
       Post component = gson.fromJson(response, Post.class); 
       System.out.println("JSON " + component.getRecentBills().get(0).getInvoiceDate()); 
       // Output: JSON 08-03-2016 (success!) 
      } 
     }, 
     new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       Log.d("ERROR", "error finalrequest => " + error.toString()); 
      } 
     } 
) { 
    @Override 
    public String getBodyContentType() { 
     return "application/x-www-form-urlencoded; charset=utf-8"; 
    } 

    // this is the relevant method 
    @Override 
    public byte[] getBody() { 

     String httpPostBody = "action=GET_CUST_BILLS&" + "user=" + CustID; 
     try { 
      httpPostBody = httpPostBody + URLEncoder.encode("", "UTF-8"); 

     } catch (UnsupportedEncodingException exception) { 

      Log.e("ERROR", "exception", exception); 
      // return null and don't pass any POST string if you encounter encoding error 
      return null; 
     } 
     Log.d("POSTBODY ", httpPostBody.toString()); 
     return httpPostBody.getBytes(); 
    } 
}; 
finalrequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 5, 
      DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); 
    TestController.getInstance().addToRequestQueue(finalrequest, "Final"); 
    } 

POJO Postクラス:

public class Post { 

    private CurrentBalanceBean currentBalance; 
    private boolean currentBalanceDisplay; 
    private Object overdueAmount; 
    private boolean overdueAmountDisplay; 
    private Object creditAmount; 
    private boolean creditAmountDisplay; 
    private int noOfBillsToShow; 

    private List<RecentBillsBean> recentBills; 

    public static Post objectFromData(String str) { 

     return new Gson().fromJson(str, Post.class); 
    } 

    public static Post objectFromData(String str, String key) { 

     try { 
      JSONObject jsonObject = new JSONObject(str); 

      return new Gson().fromJson(jsonObject.getString(str), Post.class); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    public static List<Post> arrayPostFromData(String str) { 

     Type listType = new TypeToken<ArrayList<Post>>() { 
     }.getType(); 

     return new Gson().fromJson(str, listType); 
    } 

    public static List<Post> arrayPostFromData(String str, String key) { 

     try { 
      JSONObject jsonObject = new JSONObject(str); 
      Type listType = new TypeToken<ArrayList<Post>>() { 
      }.getType(); 

      return new Gson().fromJson(jsonObject.getString(str), listType); 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return new ArrayList(); 


    } 

    public CurrentBalanceBean getCurrentBalance() { 
     return currentBalance; 
    } 

    public void setCurrentBalance(CurrentBalanceBean currentBalance) { 
     this.currentBalance = currentBalance; 
    } 

    public boolean isCurrentBalanceDisplay() { 
     return currentBalanceDisplay; 
    } 

    public void setCurrentBalanceDisplay(boolean currentBalanceDisplay) { 
     this.currentBalanceDisplay = currentBalanceDisplay; 
    } 

    public Object getOverdueAmount() { 
     return overdueAmount; 
    } 

    public void setOverdueAmount(Object overdueAmount) { 
     this.overdueAmount = overdueAmount; 
    } 

    public boolean isOverdueAmountDisplay() { 
     return overdueAmountDisplay; 
    } 

    public void setOverdueAmountDisplay(boolean overdueAmountDisplay) { 
     this.overdueAmountDisplay = overdueAmountDisplay; 
    } 

    public Object getCreditAmount() { 
     return creditAmount; 
    } 

    public void setCreditAmount(Object creditAmount) { 
     this.creditAmount = creditAmount; 
    } 

    public boolean isCreditAmountDisplay() { 
     return creditAmountDisplay; 
    } 

    public void setCreditAmountDisplay(boolean creditAmountDisplay) { 
     this.creditAmountDisplay = creditAmountDisplay; 
    } 

    public int getNoOfBillsToShow() { 
     return noOfBillsToShow; 
    } 

    public void setNoOfBillsToShow(int noOfBillsToShow) { 
     this.noOfBillsToShow = noOfBillsToShow; 
    } 

    public List<RecentBillsBean> getRecentBills() { 
     return recentBills; 
    } 

    public void setRecentBills(List<RecentBillsBean> recentBills) { 
     this.recentBills = recentBills; 
    } 

    public static class CurrentBalanceBean { 
     private int amount; 
     private String currencyCode; 

     public static CurrentBalanceBean objectFromData(String str) { 

      return new Gson().fromJson(str, CurrentBalanceBean.class); 
     } 

     public static CurrentBalanceBean objectFromData(String str, String key) { 

      try { 
       JSONObject jsonObject = new JSONObject(str); 

       return new Gson().fromJson(jsonObject.getString(str), CurrentBalanceBean.class); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return null; 
     } 

     public static List<CurrentBalanceBean> arrayCurrentBalanceBeanFromData(String str) { 

      Type listType = new TypeToken<ArrayList<CurrentBalanceBean>>() { 
      }.getType(); 

      return new Gson().fromJson(str, listType); 
     } 

     public static List<CurrentBalanceBean> arrayCurrentBalanceBeanFromData(String str, String key) { 

      try { 
       JSONObject jsonObject = new JSONObject(str); 
       Type listType = new TypeToken<ArrayList<CurrentBalanceBean>>() { 
       }.getType(); 

       return new Gson().fromJson(jsonObject.getString(str), listType); 

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return new ArrayList(); 


     } 

     public int getAmount() { 
      return amount; 
     } 

     public void setAmount(int amount) { 
      this.amount = amount; 
     } 

     public String getCurrencyCode() { 
      return currencyCode; 
     } 

     public void setCurrencyCode(String currencyCode) { 
      this.currencyCode = currencyCode; 
     } 
    } 

    public static class RecentBillsBean { 
     private String period; 
     /** 
     * amount : 22.76 
     * currencyCode : EUR 
     */ 

     private AmountBean amount; 
     private String status; 
     private String dueDate; 
     private String sortOrder; 
     private String periodType; 
     private String invoiceId; 
     private String invoiceDate; 

     public static RecentBillsBean objectFromData(String str) { 

      return new Gson().fromJson(str, RecentBillsBean.class); 
     } 

     public static RecentBillsBean objectFromData(String str, String key) { 

      try { 
       JSONObject jsonObject = new JSONObject(str); 

       return new Gson().fromJson(jsonObject.getString(str), RecentBillsBean.class); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return null; 
     } 

     public static List<RecentBillsBean> arrayRecentBillsBeanFromData(String str) { 

      Type listType = new TypeToken<ArrayList<RecentBillsBean>>() { 
      }.getType(); 

      return new Gson().fromJson(str, listType); 
     } 

     public static List<RecentBillsBean> arrayRecentBillsBeanFromData(String str, String key) { 

      try { 
       JSONObject jsonObject = new JSONObject(str); 
       Type listType = new TypeToken<ArrayList<RecentBillsBean>>() { 
       }.getType(); 

       return new Gson().fromJson(jsonObject.getString(str), listType); 

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return new ArrayList(); 


     } 

     public String getPeriod() { 
      return period; 
     } 

     public void setPeriod(String period) { 
      this.period = period; 
     } 

     public AmountBean getAmount() { 
      return amount; 
     } 

     public void setAmount(AmountBean amount) { 
      this.amount = amount; 
     } 

     public String getStatus() { 
      return status; 
     } 

     public void setStatus(String status) { 
      this.status = status; 
     } 

     public String getDueDate() { 
      return dueDate; 
     } 

     public void setDueDate(String dueDate) { 
      this.dueDate = dueDate; 
     } 

     public String getSortOrder() { 
      return sortOrder; 
     } 

     public void setSortOrder(String sortOrder) { 
      this.sortOrder = sortOrder; 
     } 

     public String getPeriodType() { 
      return periodType; 
     } 

     public void setPeriodType(String periodType) { 
      this.periodType = periodType; 
     } 

     public String getInvoiceId() { 
      return invoiceId; 
     } 

     public void setInvoiceId(String invoiceId) { 
      this.invoiceId = invoiceId; 
     } 

     public String getInvoiceDate() { 
      return invoiceDate; 
     } 

     public void setInvoiceDate(String invoiceDate) { 
      this.invoiceDate = invoiceDate; 
     } 

     public static class AmountBean { 
      private double amount; 
      private String currencyCode; 

      public static AmountBean objectFromData(String str) { 

       return new Gson().fromJson(str, AmountBean.class); 
      } 

      public static AmountBean objectFromData(String str, String key) { 

       try { 
        JSONObject jsonObject = new JSONObject(str); 

        return new Gson().fromJson(jsonObject.getString(str), AmountBean.class); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

       return null; 
      } 

      public static List<AmountBean> arrayAmountBeanFromData(String str) { 

       Type listType = new TypeToken<ArrayList<AmountBean>>() { 
       }.getType(); 

       return new Gson().fromJson(str, listType); 
      } 

      public static List<AmountBean> arrayAmountBeanFromData(String str, String key) { 

       try { 
        JSONObject jsonObject = new JSONObject(str); 
        Type listType = new TypeToken<ArrayList<AmountBean>>() { 
        }.getType(); 

        return new Gson().fromJson(jsonObject.getString(str), listType); 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

       return new ArrayList(); 


      } 

      public double getAmount() { 
       return amount; 
      } 

      public void setAmount(double amount) { 
       this.amount = amount; 
      } 

      public String getCurrencyCode() { 
       return currencyCode; 
      } 

      public void setCurrencyCode(String currencyCode) { 
       this.currencyCode = currencyCode; 
      } 
     } 
    } 
} 
+0

ボレーにはJsonRequestというクラスがありますが、それはあなたがJsonに直接アクセスできるようにすべてのことを行うためです。 – Jois

+0

@Jois、レスポンスのためのthxですが、すでに同じエラーが発生しました。 – Simon

+0

Log.v( "json response"、レスポンス)でレスポンスを記録しようとしました。 Gsonの前にgson =新しいGson();投稿コンポーネント= gson.fromJson(response、Post.class);実際のサーバーの応答が期待した応答と同じかどうかを確認してください。 – HendraWD

答えて

2

私はあなたのためにそれを明確にします。 応答は次のようになります、

{ 
    "currentBalance": { 
    "amount": 0.0, 
    "currencyCode": "EUR" 
    }, 
    "currentBalanceDisplay": true, 
    "overdueAmount": null, 
    "overdueAmountDisplay": false, 
    "creditAmount": null, 
    "creditAmountDisplay": false, 
    "noOfBillsToShow": 3, 
    "recentBills": [ 
    { 
     "period": "03 2016", 
     "amount": { 
     "amount": 12.53, 
     "currencyCode": "EUR" 
     }, 
     "status": "PAID", 
     "dueDate": "14-03-2016", 
     "sortOrder": "2548264", 
     "periodType": "MONTHLY", 
     "invoiceId": "", 
     "invoiceDate": "08-03-2016" 
    } 
    ] 
} 

しかし、あなたが得る:サーバーを所有していない場合は

"Request cannot be served without a proper action" 

、私はあなたがプロバイダからAPIを使用したとします。あなたは彼らの文書を正しく調べるべきです。私の推測では、パラメータが不足しているか、リクエストにクッキーを追加する必要があるかもしれません。

+0

Wijaya Dijono、ok私の投稿要求はまだ正しくないと思います。もっと掘り起こす必要があります。どうも。私は正しくサーバにログインしているので、そうではありません。 – Simon

+0

私はあなたの問題を解決したのか、私は再びそれを見てする必要があるかもしれません:) – HendraWD

1

Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

あなたはこのようなサーバからHTML応答を取得するとき、これは一般的なJSONの解析の問題です。

<html> 
<body> 
<h1>404 Not Found</h1> 
</body> 
</html> 

のでGsonJSONオブジェクトを期待して、適切なフォーマットが見つからない場合に例外のこのタイプをスローしています。

ここで発生するケースがいくつかあります。それぞれを確認してください。

  • あなたのメソッドはPOSTであり、サーバー側がapplication/x-www-form-urlencodedフォーマットの本文を受け入れるかどうかを確認してください。体がapplication/jsonまたはtext/plainなどを予期している可能性があります。
  • パラメータが正しく渡されているかどうかを確認してください。
  • あなたの側に何も問題がなければ、サーバー側もチェックする必要があります。それがあなたの要求を処理し、あなたが期待している適切なデータで応答できるかどうかを確認してください。

要求と応答をシミュレートするために、ポストマンを使用してみてください。これは、この種のケースのデバッグにはるかに高速です。

+0

を助けることができる@Simonうれしいですか? –

+0

はい私はそれを自分で解決しました、問題は簡単でした。私の編集を参照してください。どうも。 – Simon

2

1)は、POJOクラス 2)GsonにPOJOクラスのオブジェクトを変換するには、あなたのJSONを保管してください。

例:

@Override 
     public void onResponse(String response) { 

      Gson gson = new Gson(); 
       Post object = new Post(); 
       object.setResponse(response); 
      String gson = gson.fromJson(object, Post.class);//as you have overrided toString() it will return you the response you have set 
      System.out.println(gson); 
       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
         // Handle error 
       } 
      } 

POJO CLASS

  public class Post{ 

        private String resposne; 
       private int example; 
       .... 

       public void setResponse(String Response){ 

        this.response = Response; 
      } 

     @Override 
     public String toString() { 
      return response; 
      } 

     } 

私はこれが参考にサイモンだった願っています。ありがとう

+0

ありがとうございました!私は緑のダニを得ることはありませんか? :D – Jois