我想使用我使用HttpUrlConnection構建的客戶端應用程序讀取REST服務的GET方法的結果。該方法返回有關用戶的信息。讀完之後,我想創建一個用戶類型的對象,並填寫該用戶的所有信息。 我想我必須先將它轉換成JSON,對吧?我正在使用GSON。從JSON創建一個對象(GSON:java.lang.IllegalStateException:期望的BEGIN_OBJECT但是STRING)
我所擁有的是:
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":"[email protected]","birthdate":"2012-08-01","firstName":"Maria","lastName":"Silva","isocountrycode":"PT"}
當我做第二次印刷時,我收到:
"{\"userID\":\"user2\",\"isMale\":false,\"isObject\":false,\"telephone\":\"+911111111\",\"email\":\"[email protected]\",\"birthdate\":\"2012-08-01\",\"firstName\":\"Maria\",\"lastName\":\"Silva\",\"isocountrycode\":\"PT\"}"
但是當我嘗試pr int用戶對象我收到此錯誤:
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;
(...)
}
同樣的問題,我現在正在得到?你如何解決你的問題? – nida