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"}

当我进行第二次打印时,我收到:

"{\"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

你能告诉我我做错了什么吗?所有用户对象字段都是使用该用户类填充的。

用户等级:

    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

1

在您的 USER 类中,您必须声明 JSONObject 包含的所有数据类型,不多也不少。铁: class User { String UserID = ""; Boolean isMale;}

等等。

否则 GSON.toJson(); 将不起作用并引发异常。

于 2013-03-31T14:55:13.727 回答