标签:json java type-conversion parsing gson
我想使用我使用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\"}"
但是当我尝试打印User对象时,我收到此错误:
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;
(...)
}
解决方法:
在您的USER类中,您必须声明JSONObject包含的所有数据类型,而不是更多而不是更少.
F.e:
class User {
String UserID =“”;
Boolean isMale;}
等等.
否则GSON.toJson();将无法工作并抛出异常.
标签:json,java,type-conversion,parsing,gson 来源: https://codeday.me/bug/20190709/1410537.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。