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:

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

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:

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.


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

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

Post a Comment for "Sending Complex JSON Object"