java-发送复杂的JSON对象

我想与Web服务器通信并交换JSON信息.

我的网络服务网址如下所示:http://46.157.263.140/EngineTestingWCF/DPMobileBookingService.svc/SearchOnlyCus

这是我的JSON请求格式.

{
    "f": {
        "Adults": 1,
        "CabinClass": 0,
        "ChildAge": [
            7
        ],
        "Children": 1,
        "CustomerId": 0,
        "CustomerType": 0,
        "CustomerUserId": 81,
        "DepartureDate": "/Date(1358965800000+0530)/",
        "DepartureDateGap": 0,
        "Infants": 1,
        "IsPackageUpsell": false,
        "JourneyType": 2,
        "PreferredCurrency": "INR",
        "ReturnDate": "/Date(1359138600000+0530)/",
        "ReturnDateGap": 0,
        "SearchOption": 1
    },
    "fsc": "0"
}

我尝试使用以下代码发送请求:

public class Fdetails {
    private String Adults = "1";
    private String CabinClass = "0";
    private String[] ChildAge = { "7" };
    private String Children = "1";
    private String CustomerId = "0";
    private String CustomerType = "0";
    private String CustomerUserId = "0";
    private Date DepartureDate = new Date();
    private String DepartureDateGap = "0";
    private String Infants = "1";
    private String IsPackageUpsell = "false";
    private String JourneyType = "1";
    private String PreferredCurrency = "MYR";
    private String ReturnDate = "";
    private String ReturnDateGap = "0";
    private String SearchOption = "1";
}

public class Fpack {
    private Fdetails f = new Fdetails();
    private String fsc = "0";
}

然后使用Gson创建如下的JSON对象:

public static String getJSONString(String url) {
String jsonResponse = null;
String jsonReq = null;
Fpack fReq = new Fpack();

try {                                                
    Gson gson = new Gson();
    jsonReq = gson.toJson(fReq);                        
    JSONObject json = new JSONObject(jsonReq);
    JSONObject jsonObjRecv = HttpClient.SendHttpPost(url, json);
    jsonResponse = jsonObjRecv.toString();
} 
catch (JSONException e) {
                           e.printStackTrace();
                }               
return jsonResponse;
    }

而我的HttpClient.SendHttpPost方法是

public static JSONObject SendHttpPost(String URL, JSONObject json) {

        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPostRequest = new HttpPost(URL);

            StringEntity se;
            se = new StringEntity(json.toString());
            httpPostRequest.setEntity(se);
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));          
            HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // Read the content stream
                InputStream instream = entity.getContent();
                Header contentEncoding = response.getFirstHeader("Content-Encoding");
                if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    instream = new GZIPInputStream(instream);
                }

                // convert content stream to a String
                String resultString= convertStreamToString(instream);
                instream.close();
                resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

                // Transform the String into a JSONObject
                JSONObject jsonObjRecv = new JSONObject(resultString);
            return jsonObjRecv;
            } 
    catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

现在,我得到以下异常:

org.json.JSONException: Value !DOCTYPE of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:158)
at org.json.JSONObject.<init>(JSONObject.java:171)

在我发出请求之前,JSON字符串的打印输出如下:

{
    "f": {
        "PreferredCurrency": "MYR",
        "ReturnDate": "",            
        "ChildAge": [
            7
        ],
        "DepartureDate": "Mar 2, 2013 1:17:06 PM",
        "CustomerUserId": 0,
        "CustomerType": 0,
        "CustomerId": 0,
        "Children": 1,
        "DepartureDateGap": 0,
        "Infants": 1,
        "IsPackageUpsell": false,
        "JourneyType": 1,
        "CabinClass": 0,
        "Adults": 1,
        "ReturnDateGap": 0,
        "SearchOption": 1

    },
    "fsc": "0"
}

如何解决此异常?提前致谢!

解决方法:

要创建一个附加了JSON对象的请求,您应该执行以下操作:

public static String sendComment (String commentString, int taskId, String    sessionId, int displayType, String url) throws Exception
{
    Map<String, Object> jsonValues = new HashMap<String, Object>();
    jsonValues.put("sessionID", sessionId);
    jsonValues.put("NewTaskComment", commentString);
    jsonValues.put("TaskID" , taskId);
    jsonValues.put("DisplayType" , displayType);
    JSONObject json = new JSONObject(jsonValues);

    DefaultHttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost(url + SEND_COMMENT_ACTION);

    AbstractHttpEntity entity = new ByteArrayEntity(json.toString().getBytes("UTF8"));
    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setEntity(entity);
    HttpResponse response = client.execute(post);

    return getContent(response);    
}
上一篇:java-为什么Gson会将Integer解析为Double?


下一篇:java-为什么Gson会漂亮地打印到控制台,而不是文件?