所以我使用谷歌的GSON库来理解JSON字符串。我让它在我保存的对象User
处工作,其语句如下:
User user = gson.fromJson(string, User.class),
但我似乎无法理解如何使用"嵌套对象保存字符串。"这是给我错误的陈述:
Gson gson = new Gson();
Request request = gson.fromJson(requestInput, Request.class);
requestInput
String requestInput = "{key: \"123\", requestType: \"POST\", requestModelType: \"USER\","
+ " obj: {username: \"alex\", email: \"email@gmail.com\", password:\"pass\"}}";
我的User
课程如下:
public class User implements Serializable{
private static final long serialVersionUID = -24243416292823789L;
private String username;
private String email;
private String password;
private List<Circle> circles;
private List<Notification> notifications;
...
我的Request
看起来像这样:
public class Request {
private String key;
private String requestType;
private String requestModelType;
private User user;
...
最后,我收到以下错误:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
...
非常感谢任何有关更好设计的建议或建议!
答案 0 :(得分:1)
您需要使用:
@SerializedName(&#34;物镜&#34) 私人用户用户;
因此GSON知道&#34; obj&#34;在您的JSON中应该映射到用户字段。
您显示的实际错误有点不同,我不确定您是如何获得该特定错误的 - 这意味着您在Java中声明为String但在JSON中声明为Object。 / p>