4

HttpUrlConnection を使用して構築したクライアント アプリケーションを使用して、REST サービスの GET メソッドの結果を読み取りたいと考えています。そのメソッドは、ユーザーに関する情報を返します。それを読んだ後、その User のすべての情報が入力されたUser タイプのオブジェクトを作成したいと思います。最初にJSONに変換する必要があると思いますよね?GSONを使用しています。

私が持っているものは次のとおりです。

if(urlConnection.getResponseCode()==200)
{
   String response ="";
   Scanner inStream = new Scanner(urlConnection.getInputStream());

   while(inStream.hasNextLine())
      response+=(inStream.nextLine());
   System.out.println(response);

   //JSON
   Gson gson = new Gson();
   String json = gson.toJson(response);
   System.out.println(json);

   // User Object
   User object = new User();
   object = gson.fromJson(json, User.class);
   System.out.println(object);

}

最初の印刷を行うと、次のものが表示されます。

{"userID":"user2","isMale":false,"isObject":false,"telephone":"+911111111","email":"maug@abc.pt","birthdate":"2012-08-01","firstName":"Maria","lastName":"Silva","isocountrycode":"PT"}

2 番目の印刷を行うと、次のものが表示されます。

"{\"userID\":\"user2\",\"isMale\":false,\"isObject\":false,\"telephone\":\"+911111111\",\"email\":\"maug@abc.pt\",\"birthdate\":\"2012-08-01\",\"firstName\":\"Maria\",\"lastName\":\"Silva\",\"isocountrycode\":\"PT\"}"

しかし、ユーザー オブジェクトを印刷しようとすると、次のエラーが表示されます。

    com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 226
    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:761)
    at com.google.gson.Gson.fromJson(Gson.java:710)
    at com.google.gson.Gson.fromJson(Gson.java:682)
    at httpURLconnection.UserGetUserInfo.main(UserGetUserInfo.java:70)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 226
    at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
    ... 5 more

私が間違っていることを教えてもらえますか?すべての User オブジェクト フィールドは、その User クラスを使用して埋められました。

ユーザークラス:

    public class User {
    String  userID        = null;
    boolean isMale        = false;
    boolean isObject      = false;
    String  Telephone     = null;
    String  Email         = null;
    Date    Birthdate     = null;
    String  FirstName     = null;
    String  LastName      = null;
    String  ISOcountrycode   = null;

    (...) 
    }
4

1 に答える 1