Revision: 936
          http://jwebunit.svn.sourceforge.net/jwebunit/?rev=936&view=rev
Author:   jevonwright
Date:     2012-02-14 23:35:26 +0000 (Tue, 14 Feb 2012)
Log Message:
-----------
adding FAQ entry on parsing JSON with JWebUnit

Modified Paths:
--------------
    trunk/src/site/fml/faq.fml

Modified: trunk/src/site/fml/faq.fml
===================================================================
--- trunk/src/site/fml/faq.fml  2012-01-27 09:43:35 UTC (rev 935)
+++ trunk/src/site/fml/faq.fml  2012-02-14 23:35:26 UTC (rev 936)
@@ -54,6 +54,35 @@
 Have a look at http://htmlunit.sourceforge.net/submittingJSBugs.html
       </answer>
     </faq>
+    
+    <faq id="javascript-json">
+      <question>
+       How can I parse JSON output using JWebUnit or HtmlUnit?
+      </question>
+      <answer>
+        <p>HtmlUnit, one of the underlying engines of JWebUnit, <a 
href="http://stackoverflow.com/questions/2932857/html-handling-a-json-response";>does
 not support direct
+        execution of Javascript functions</a>. You need to check beforehand 
that the <code>Content-Type</code>
+        of the response is <code>application/json</code>, and then use a 
different library to parse it.</p>
+        
+        <p>For example, <a href="http://code.google.com/p/google-gson/";>Google 
Gson</a> can be used to parse JSON, as follows:</p>
+        
+        <source>WebResponse response = ((HtmlUnitTestingEngineImpl) 
JWebUnit.getTestingEngine()).getWebResponse();
+               
+// check content type
+assertTrue("Response type should be application/json, was: " + 
response.getContentType(), 
"application/json".equals(response.getContentType()));
+
+// parse JSON
+Gson gson = new Gson();
+String json = response.getContentAsString();
+JsonObject obj = new JsonParser().parse(json).getAsJsonObject(); // or 
JsonArray, depending on the JSON content
+
+assertTrue("Object should have success field", obj.has("success"));
+String success = gson.fromJson(obj.get("success"), String.class);
+String username = gson.fromJson(obj.get("username"), String.class);
+String type = gson.fromJson(obj.get("type"), String.class);
+// etc</source> 
+      </answer>
+    </faq>
   </part>
   
     <part id="JUnitPerf">

This was sent by the SourceForge.net collaborative development platform, the 
world's largest Open Source development site.


------------------------------------------------------------------------------
Keep Your Developer Skills Current with LearnDevNow!
The most comprehensive online learning library for Microsoft developers
is just $99.99! Visual Studio, SharePoint, SQL - plus HTML5, CSS3, MVC3,
Metro Style Apps, more. Free future releases when you subscribe now!
http://p.sf.net/sfu/learndevnow-d2d
_______________________________________________
JWebUnit-development mailing list
JWebUnit-development@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/jwebunit-development

Reply via email to