1

I want to communicate with a web server and exchange JSON information.

my webservice URL looking like following format: http://46.157.263.140/EngineTestingWCF/DPMobileBookingService.svc/SearchOnlyCus

Here is my JSON Request format.

{
    "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"
}

I tried with the following code to send a request:

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";
}

Then using Gson I create the JSON object like:

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;
    }

and my HttpClient.SendHttpPost method is

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;
    }

Now I get the following exception:

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)

and the printout of JSON string right before I make the request is as follows:

{
    "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"
}

How do I solve this exception? Thanks in advance!

bCliks
  • 2,918
  • 7
  • 29
  • 52

4 Answers4

3

I'm not quite familiar with Json, but I know it's pretty commonly used today, and your code seems no problem.

How to convert this JSON string to JSON object?

Well, you almost get there, just send the JSON string to your server, and use Gson again in your server:

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

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

About the Exception:

You should remove this line, because you are sending a request, not responsing to one:

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

And I would change this line:

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

to

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

If this doesn't make any difference, please print out your JSON string before you send the request, let's see what's in there.

Crono
  • 10,211
  • 6
  • 43
  • 75
WoooHaaaa
  • 19,732
  • 32
  • 90
  • 138
  • Thanks for your answer. but when i send the json string to my server, i got this warning `org.json.JSONException: Value – bCliks Mar 02 '13 at 07:40
  • @bala How do you send this string ? Did you get the Exception in server side or client side ? – WoooHaaaa Mar 02 '13 at 08:56
  • //Did you get the Exception in server side or client side ?// i got that Exception in client side.. //How do you send this string ?// I update my question about that.. please see..and help me.. – bCliks Mar 02 '13 at 10:44
  • as you say I made changes, but now i got this exception.. `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.(JSONObject.java:158) at org.json.JSONObject.(JSONObject.java:171)` I update the printout of json string before send the request, please see.. – bCliks Mar 02 '13 at 11:47
  • @bala - from the two exception stacktraces you posted, there is some (possibly hidden) XML content in your JSON string. Are you using a JSON object to convert the incoming JSON string on the server side? Post the full resource method (from the server side) to your question please. – Perception Mar 02 '13 at 11:54
  • @Perception //Are you using a JSON object to convert the incoming JSON string on the server side?// I did not get what you say.. i make the request on Client side(in Android Application). I am not the control of Server side. I am using JSON object for receiving the Response from server. And I have a new doubt, the following URL is provide the webservice for me.. http://44.139.273.200/EngineTestingWCF/MobileBookingService.svc/SearchOnly In API Document they are mention the JSON Sample Request format that is in my Question.. is this correct way i am going?? plese help me.. – bCliks Mar 02 '13 at 12:19
  • @bala - ok, now we are getting somewhere. Your current code does not show a JSONObject at all (so I just assumed server side). Two things, include in your question where you are getting the response from the server, and converting it into a JSONObject. Also, print out the response string from the server and add that too your question as well. – Perception Mar 02 '13 at 12:26
  • @Perception How you assumed server side? Actually i consume the webservice by making a request with jsonObject parameter and expecting the response from server. So I think I am on Client side. i am totally changed my question with my current code.. please see.. – bCliks Mar 02 '13 at 12:59
  • @bala - I'm almost 100% sure your server is returning you XML. Add an Accept header before sending the request - `httpPostRequest.addHeader("Accept", "application/json");`. – Perception Mar 02 '13 at 13:05
  • @Perception After adding `httpPostRequest.addHeader("Accept", "application/json");` `httpPostRequest.setHeader(HTTP.CONTENT_TYPE, "application/json");` this lines now i get the following Exception `org.json.JSONException: Value (JSONObject.java:158) at org.json.JSONObject.(JSONObject.java:171) ` How do I solve this exception? – bCliks Mar 02 '13 at 13:15
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/25420/discussion-between-perception-and-bala) – Perception Mar 02 '13 at 13:18
3

To create a request with JSON object attached to it what you should do is the following:

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);    
}
Emil Adz
  • 40,709
  • 36
  • 140
  • 187
0

From what I have understood you want to make a request to the server using the JSON you have created, you can do something like this:

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(); 
      }
    }
  }
vikasing
  • 11,562
  • 3
  • 25
  • 25
0

Actually it was a BAD REQUEST. Thats why server returns response as XML format. The problem is to convert the non primitive data(DATE) to JSON object.. so it would be Bad Request.. I solved myself to understand the GSON adapters.. Here is the code I used:

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));                             
                            }
                        };
bCliks
  • 2,918
  • 7
  • 29
  • 52