heartwilltell
heartwilltell

Reputation: 96

Convert POST to Json with Java

I have simple Post request

POST /savings HTTP/1.1
Host: localhost:4567
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded

Body:
name=username&description=userdescription

I wonder how to convert post body name=username&description=userdescription to Json like:

{
"name": "username", 
"description": "userdescription"
}

Any ideas, Im using http://sparkjava.com and I need handle post request with content-type: application/x-www-form-urlencoded

post("/user", (request, response) -> {
// .. Convert request to User object
});

Upvotes: 1

Views: 4448

Answers (3)

Tom
Tom

Reputation: 59

I personally do this using Google Gson and request objects.

It's worth noting this won't work if you're using URL parameters.

EDIT: The UserRequest object will be null if any of the parameters are missing as gson won't be able to build the object.

import java.io.InputStreamReader;
import com.google.gson.Gson;

import spark.Spark;

public class Handler
{
    private final Gson gson = new Gson();

    public Handler()
    {
    }

    public void init()
    {
        Spark.post("/user", (req, resp) -> {
            final UserRequest userRequest = gson.fromJson(new InputStreamReader(req.raw().getInputStream()), UserRequest.class);
            //do something with user
            return new Object();
        });
    }

    private static class UserRequest
    {
        private String name;
        private String description;

        public String getDescription()
        {
            return description;
        }

        public String getName()
        {
            return name;
        }
    }

    public static void main(final String[] args)
    {
        final Handler handler = new Handler();
        handler.init();
    }
}

Upvotes: 0

cнŝdk
cнŝdk

Reputation: 32145

You can use request.getParameter(String param) method to get your parameters values from your POST request.

I assume you are using a servlet, so you can do the follwing in your doPost() method:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String name = request.getParameter("name");
    String description = request.getParameter("description");


        JSONObject json = new JSONObject();
        json.put("name", (name==null || name.isEmpty() ? "" : name));
        json.put("description", (description==null || description.isEmpty())? "" : description);

}

And you will get the json you need:

{
  "name": "username", 
  "description": "userdescription"
}

All credits go to HttpServletRequest get JSON POST data.

Upvotes: 1

I assume you get your parameters from the URL in a servlet, don't you?

Anyway, as an exercise with Regex, I would do this:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class Any {


public static String queryStringToJasonParser(final String queryString){


    try {
            Pattern regex = Pattern.compile("(^|\\s+)name=(.*?)&description=(.*?)(\\s+|$)");
            Matcher regexMatcher = regex.matcher(queryString);

            if(regexMatcher.matches()){

                final String nameValue = regexMatcher.group(2);
                final String descriptionValue = regexMatcher.group(3);


                return "{\"name\": \""+nameValue+"\", \"description\": \""+descriptionValue+"\"}";


            }


    } catch (PatternSyntaxException ex) {
           //TODO: Handle it.
    }
    return "{\"name\": \"\", \"description\": \"\"}";

}



public static void main(String[] args){
    final String resultJason = Any.queryStringToJasonParser("name=wow1&description=wow2");
    System.out.println(resultJason);

    final String resultJason1 = Any.queryStringToJasonParser("name=&description=wow2");
    System.out.println(resultJason1);

}

}

add any desired optimization

Regards

Upvotes: 0

Related Questions