Search code examples
javajsonjson-simple

How to parse json request in java spark


I am trying to parse JSON object that is sent using HTTP post "body" request in java-spark. For example if I send JSON object like :

{\"name"\ : \"john\", \"age\":\"300\"}

. I want to get the name and age in different strings. I have tried this so far in java-spark :

post("/test", "application/json", (req,res) -> {
 String name = req.queryParams("name");
 return "hi : " +  name;
});

but it returns hi : null as result.

I searched a lot on the internet but I keep finding complicated results, is there a simple way? Note : This is not Apache spark.

EDIT : I have managed to add JSON-simple lib as a dependency in pom.xml, and I tried the following :

JSONObject obj = new  JSONObject(req.body());

But I get an error :

String cannot be converted to map

Although that line works in my android development.


Solution

  • First of all please validate whether the string you are getting is in proper JSON format or not. And to validate that you can use Validate JSON.

    Once it is validated you can try following thing.

    I beleive instead of JSONObject you should have used its parse to parse JSON.

    For example :

    JSONParser parser = new JSONParser();
    String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
    Object obj = parser.parse(s);
    JSONArray array = (JSONArray)obj;
    

    Try below links which I hope will help you to understand better.

    JSON Parser1

    JSON Parser2