所以我使用 Google 的 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;
...
我的请求
如下所示:
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)
...
非常感谢对此的任何帮助或更好设计的建议!
最佳答案
您需要使用:
@SerializedName("obj") 私有(private)用户用户;
这样 GSON 就知道 JSON 中的“obj”应该映射到用户字段。
您显示的实际错误有点不同,我不确定您是如何得到该特定错误的 - 这意味着您在 Java 中声明为字符串,但在 JSON 中声明为对象。
关于java - 尝试将 JSON(使用 GSON)读入一个具有另一个对象作为字段的对象。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24399435/