Skip to content Skip to sidebar Skip to footer

Sending Complex Json Object

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/DPMobileBookingServic

Solution 1:

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

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

    DefaultHttpClient client = newDefaultHttpClient();

    HttpPost post = newHttpPost(url + SEND_COMMENT_ACTION);

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

    returngetContent(response);    
}

Solution 2:

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:

Gsongson=newGson();
Fpackf= 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(newBasicHeader(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.

Solution 3:

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;
    HttpURLConnectionconnection=null;
    StringurlParameters="json="+ jsonSend;  
    try {
      url = newURL(targetURL);
      connection = (HttpURLConnection)url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", 
           "application/x-www-form-urlencoded");
      connection.setRequestProperty("Content-Language", "en-US");  
      DataOutputStreamwr=newDataOutputStream (
                  connection.getOutputStream ());
      wr.writeBytes (urlParameters);
      wr.flush ();
      wr.close ();

      InputStreamis= connection.getInputStream();
      BufferedReaderrd=newBufferedReader(newInputStreamReader(is));
      String line;
      StringBufferresponse=newStringBuffer(); 
      while((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
      }
      rd.close();
      return response.toString();

    } catch (Exception e) {

      e.printStackTrace();
      returnnull;

    } finally {

      if(connection != null) {
        connection.disconnect(); 
      }
    }
  }

Solution 4:

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 = newJsonSerializer<Date>() {

                            @OverridepublicJsonElementserialize(Date src, Type typeOfSrc,
                                    JsonSerializationContext comtext) {

                                return src == null ? null : newJsonPrimitive("/Date("+src.getTime()+"+05300)/");
                            }
                        };
                        JsonDeserializer<Date> deser = newJsonDeserializer<Date>() {                           
                            @OverridepublicDatedeserialize(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 : newDate(Long.parseLong(tmpDate));                             
                            }
                        };

Post a Comment for "Sending Complex Json Object"