2013-01-11 43 views
1

我试图发送一些简单的字符串来测试我的servlet和小应用程序之间的数据传输 (servlet - > applet,而不是applet - > servlet),使用Json格式和Gson库。 小程序中产生的字符串应该与原始消息完全相同,但事实并非如此。 我得到9个字符<!DOCTYPE字符串代替。JSON反序列化失败? (servlet->小程序通信)

编辑:它看起来像servlet返回的HTML网页,而不是JSON,不是吗?
edit2:在NetBeans中使用“运行文件”命令激活servlet时,消息在浏览器中正确显示。

能否请你在我的代码来看看:

的Servlet:

//begin of the servlet code extract 
protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException 
{ 
    PrintWriter out = response.getWriter(); 
    try 
    { 
     String action; 
     action = request.getParameter("action"); 
     if ("Transfer".equals(action)) 
     { 
      sendItToApplet(response); 
     } 
    } 
    finally 
    { 
     out.close(); 
    } 
} 

public void sendItToApplet(HttpServletResponse response) throws IOException 
{ 
    String messageToApplet = new String("my message from the servlet to the applet"); 
    String json = new Gson().toJson(messageToApplet); 
    response.setContentType("application/json"); 
    response.setCharacterEncoding("UTF-8"); 

    Writer writer = null; 
    writer = response.getWriter(); 
    writer.write(json); 
    writer.close(); 
} 
//end of the servlet code extract 

小程序:

//begin of the applet code extract 
public void getItFromServlet() throws MalformedURLException, IOException, ClassNotFoundException 
{ 
    URL urlServlet = new URL("http://localhost:8080/Srvlt?action=Transfer"); 
    URLConnection connection = urlServlet.openConnection(); 
    connection.setDoInput(true); 
    connection.setDoOutput(true); 
    connection.setUseCaches(false); 
    connection.setRequestProperty("Content-Type", "application/json"); 

    InputStream inputStream = connection.getInputStream(); 
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); 
    JsonReader jr = new JsonReader(br); 
    String retrievedString = new Gson().fromJson(jr, String.class); 
    inputStream.close(); 
    jtextarea1.setText(retrievedString); //jtextarea is to display the received string from the servlet in the applet 
} 
//end of the applet code extract 
+0

那么......当您使用浏览器或curl测试时,您的servlet会返回什么结果? –

+0

它返回的是简单格式的页面,其值为“String messageToApplet”,仅此而已。 – BMC

+0

如果您只需要在Servlet和Applet之间传输一个字符串,那么使用JSON并不是必需的,而是一个开销。顺便说一句,你需要清理你的代码。 –

回答

1

的问题是,你不能从你的servlet发送JSON,正如你从你的评论中发现的那样。这是因为... Gson对你想要做什么感到困惑。

如果您在servlet中测试JSON序列化(从toJson()的输出),您会发现...它没有做任何事情,只是将String的内容用引号括起来。 JSON基于对象的文本表示(类的字段为值),并且它肯定不想用String对象来实现;那么默认的序列化就是将String内容放入生成的JSON中。

编辑补充:为GSON一个典型的应用会是这样的:

class MyClass { 
    String message = "This is my message"; 
} 

...

String json = new Gson().toJson(new MyClass()); 

产生的JSON是:

{ “message”:“这是我的信息”}

+0

我明白了,谢谢。我应该创建一个类并发送它,而不是一个简单的字符串。现在我得到一个像上面一样的正确的JSON。 – BMC