1

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

我的网络服务 URL 看起来像以下格式: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"
}

我该如何解决这个异常?提前致谢!

4

4 回答 4

3

我对 Json 不是很熟悉,但我知道它现在很常用,而且你的代码似乎没有问题。

如何将此 JSON 字符串转换为 JSON 对象?

好吧,你差不多到了,只需将 JSON 字符串发送到你的服务器,然后在你的服务器中再次使用 Gson:

Gson gson = new Gson();
Fpack f = gson.fromJSON(json, Fpack.class);

http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html

关于例外:

您应该删除此行,因为您正在发送请求,而不是响应:

httpPostRequest.setHeader("Accept", "application/json");

我会改变这一行:

httpPostRequest.setHeader("Content-type", "application/json"); 

se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

如果这没有任何区别,请在发送请求之前打印出您的 JSON 字符串,让我们看看里面有什么。

于 2013-03-02T06:30:16.413 回答
3

要创建附加了 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);    
}
于 2013-03-02T06:38:36.277 回答
0

据我了解,您想使用您创建的 JSON 向服务器发出请求,您可以执行以下操作:

URL url;
    HttpURLConnection connection = null;
    String urlParameters ="json="+ jsonSend;  
    try {
      url = new URL(targetURL);
      connection = (HttpURLConnection)url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", 
           "application/x-www-form-urlencoded");
      connection.setRequestProperty("Content-Language", "en-US");  
      DataOutputStream wr = new DataOutputStream (
                  connection.getOutputStream ());
      wr.writeBytes (urlParameters);
      wr.flush ();
      wr.close ();

      InputStream is = connection.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
      String line;
      StringBuffer response = new StringBuffer(); 
      while((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
      }
      rd.close();
      return response.toString();

    } catch (Exception e) {

      e.printStackTrace();
      return null;

    } finally {

      if(connection != null) {
        connection.disconnect(); 
      }
    }
  }
于 2013-03-02T06:51:33.977 回答
0

实际上这是一个错误的请求。这就是服务器以 XML 格式返回响应的原因。问题是将非原始数据(DATE)转换为 JSON 对象..所以这将是错误请求..我解决了自己以了解 GSON 适配器..这是我使用的代码:

try {                                                       
                        JsonSerializer<Date> ser = new JsonSerializer<Date>() {

                            @Override
                            public JsonElement serialize(Date src, Type typeOfSrc,
                                    JsonSerializationContext comtext) {

                                return src == null ? null : new JsonPrimitive("/Date("+src.getTime()+"+05300)/");
                            }
                        };
                        JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {                           
                            @Override
                            public Date deserialize(JsonElement json, Type typeOfT,
                                    JsonDeserializationContext jsonContext) throws JsonParseException {

                                String tmpDate = json.getAsString();

                                  Pattern pattern = Pattern.compile("\\d+");
                                  Matcher matcher = pattern.matcher(tmpDate);
                                  boolean found = false;

                                  while (matcher.find() && !found) {
                                       found = true;
                                        tmpDate = matcher.group();
                                  }
                                return json == null ? null : new Date(Long.parseLong(tmpDate));                             
                            }
                        };
于 2013-03-12T04:56:01.017 回答