-2

The method below is hit or miss if it parses the request properly...

Here is what the request looks like:

POST /addEvent/ HTTP/1.1
Host: localhost:1234
Content-Type: multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY
Accept-Encoding: gzip, deflate
Content-Length: 201
Accept-Language: en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, nl;q=0.6, it;q=0.5
Accept: application/json
Connection: keep-alive
User-Agent: XXXXXXXXXXXXXXXXXX

--Boundary+0xAbCdEfGbOuNdArY
Content-Disposition: form-data; name="userInfo"

{   "user_id" : 1,   "value" : "Water",   "typeCode" : "Searched" } 

Here is how we are extracting it now...

//Key where the request begins
String keyString = "\"userInfo\"";

//Get the index of the key
int end = bufferedJson.lastIndexOf("\"userInfo\"");

//Create substring at beginning of the json
String json = bufferedJson.substring(end+keyString.length(), bufferedJson.length());

//Convert json to feed item
Gson gson = new Gson();
Event eventItem = gson.fromJson(json, Event.class);

I get this error pretty often:

Expected BEGIN_OBJECT but was STRING at line 1 column 1

How can we parse this efficiently?

Bobulous
  • 12,967
  • 4
  • 37
  • 68
William Falcon
  • 9,813
  • 14
  • 67
  • 110

3 Answers3

1

Use Apache HTTP Client 4 to read Http response body in a convenient way. If you need to marshall your json further to a java object then make use of jackson. Here is the sample code:

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * This example demonstrates the use of the {@link ResponseHandler} to simplify
 * the process of processing the HTTP response and releasing associated resources.
 */
public class ClientWithResponseHandler {

    public final static void main(String[] args) throws Exception {

        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("http://www.google.com/");

            System.out.println("executing request " + httpget.getURI());

            // Create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            // Body contains your json stirng
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
            System.out.println("----------------------------------------");

        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }

}
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

To parse this better:

  • First, it seems like you're taking a "raw" HTTP POST request, and then reading it line by line using BufferedReader (your comment suggests this), this way you'll lose the new line chars; if you are going to do so, add a new line ("\n") every time you read a line to your final String, this way it doesn't lose the new lines and facilitates the things for the next step.

  • Now, with this final String, you can use this:

    String json = null;
    
    Pattern pattern = Pattern.compile("\n\n");
    Matcher matcher = pattern.matcher(myString); // myString is the String you built from your header
    if(matcher.find() && matcher.find()) {
        json = myString.substring(matcher.start() + 2);
    } else {
        // Handle error: json string wasn't found
    }
    

CAVEATS: this works if:

  • POST Request will always be multipart/form-data
  • There are not other parameters in the request
  • you STOP reading the request as soon as you find your json data
  • you included "\n" every time you read a line as I said in the first step

Personally I wouldn't read the raw HTTP header, I'd rather use Apache commons FileUpload or the like, but if your are going to do it this way, I think this is the less terrible solution.

morgano
  • 17,210
  • 10
  • 45
  • 56
0

You can use

gson().fromJson(request.getReader(), Event.class);

or

String json = request.getReader().readLine();
gson().fromJson(json, Event.class);
Diego Plentz
  • 6,760
  • 3
  • 30
  • 31