protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(request.getParameter("msg").toString());
String data = request.getParameter("msg").toString();
Gson gson = new Gson();
MessageBase msggg = gson.fromJson(data, MessageBase.class);
//System.out.println(msggg.Id + msggg.MessageText);
}
public abstract class MessageBase implements Serializable {
public int Id;
public String MessageText;
public Date ReceiveDate;
}
public class SyncSmsMessage extends MessageBase {
public String SenderNum;
}
该代码在
MessageBase msggg=gson.fromJson(data, MessageBase.class);
之前有效。我得到这个异常:java.lang.RuntimeException: Failed to invoke public com.example.syncapp.MessageBase() with no args
at com.google.gson.internal.ConstructorConstructor$2.construct(ConstructorConstructor.java:94)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:162)
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 AndroidServlet.doPost(AndroidServlet.java:75)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
我需要做什么?
我把.jar放到lib文件夹中,我认为tomcat很好地加载了.jar。
最佳答案
从GSON User Guide:
您的问题是GSON的实例创建者需要在要反序列化JSON响应的类中使用无参数构造函数,即MessageBase
。
否则,您需要编写自己的实例创建器,例如this。