0

私はJSONこのようなものを受け取ることになっています

{
    "browse": [
        {
            "title": "Program Translations"
        }
    ],
    "errorno": "fe_200",
    "message": "Your browse history"
}

しかし、ブラウズ情報がないため、このように取得します..

{"errorno":"fe_3946","message":"No browse history found.","browse":"NULL"}

これは完全に正常です。

私はこのようなJavaクラスを書きました..

class BrowseHistoryJson {

      public BrowseHistoryJson() {}

      private String errorno;
      private String message;
      private List<Browse> browse;
      // other attributes

      public String getErrorNo() {
        return errorno;
      }
      public String getMessage() {
            return message;
          }
      public List<Browse> getResults() { return browse; }
      public void setErrorNo(String errorno) {
            this.errorno = errorno;
          }
      public void setMessage(String message) {
        this.message = message;
      }

      public void setResults(List<Browse> browse) { this.browse = browse; }
      public String toString() { return "Results[" + browse + "]";}


      static class Browse {
            private String title;


            public String getTitle() {
                return title;
            }


            public void setTitle(String title) {
                this.title = title;
            }


            public String toString() { return "Result[title:" + title +"]"; }
        }

    }

今、ステートメントを実行すると

BrowseHistoryJson 結果 = new Gson().fromJson(リーダー, BrowseHistoryJson.class);

私は次のような例外を取得しています

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 74   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:795)
at com.google.gson.Gson.fromJson(Gson.java:734)

の配列でデータを取得すると、完全に正常に動作しbrowseます。

nullこの値がnullになる可能性があることを事前に宣言する方法など、処理を追加する方法は?

JSON のメモを確認し、インターネットで検索しましたが、あまり役に立ちませんでした。

4

1 に答える 1

1

GsonBuilder オブジェクトを使用して Gson オブジェクトを作成する必要があります。

Gson gson = new GsonBuilder().serializeNulls().create();//handle null

このようにすると、gson は null を適切に処理します。

于 2013-03-29T19:02:54.187 に答える