0

I have following request mapping:

@RequestMapping(value = "/reCalculated", method = RequestMethod.POST)
public @ResponseBody void reCalculated(JSONObject obj) {

    obj.
}

and then i have incoming json

{"params":{"date_a":"2017-05-01","date_b":"2017-05-02"}}

but in java, obj. only gives me options toString() and toJSONString() meanwhile all the tutorials, and few threads clearly tell me i should be able to do obj.getJSONObject("params") Why is this? how can i access my parameters?

<dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1.1</version>
 </dependency>

is the dependency.

1
  • Why are you not considering defining a POJO data model and map the @RequestBody to it? Commented Nov 23, 2018 at 8:44

2 Answers 2

1

json-simple library had method get(String name) and need external type casting like below

String name = (String) jsonObject.get("name");
JSONArray msg = (JSONArray) jsonObject.get("messages");
long age = (Long) jsonObject.get("age");

But gson library has predefined methods here

public JsonObject getAsJsonObject(String memberName)
public JsonArray getAsJsonArray(String memberName)

Maven dependency

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.3</version>
</dependency>
Sign up to request clarification or add additional context in comments.

Comments

1

You can get JSONString from your param

Gson gson = (new GsonBuilder()).create();
jsonString = obj.get("params").getAsString();
JsonObject param= gson.fromJson(jsonString, JsonObject.class);

As Deadpool said, you want to use gson but you added json-simple dependency.

Comments

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.