3

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that was exactly what I needed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.