Home > database >  How can i get json indexes as keys?
How can i get json indexes as keys?

Time:04-23

The user of the api sends a json like this:

{ "0": "3♥", "1": "5♣", "2": "4♣",“3”: “9♥”, … }

im trying to save the the value of each index (3♥,5♣,4♣,9♥) in a list.

all I have now is the POST method but I dont know how to read it) OR i don't know if i need to use another type of request

 @RequestMapping(value="/start", method = RequestMethod.POST, consumes= "application/json" )
public String getData(@RequestBody ?? ) { }

thank you in advance

CodePudding user response:

Try below

   @RequestMapping(value="/start", method = RequestMethod.POST, consumes= "application/json" )
    public String getData(@RequestBody HashMap<String, String> data) {
        List<String> result = new ArrayList<>();

        for (String val: data.values()){
        result.add(val);
        }
     }

We are storing the user input into a HashMap and then extracting its values in the for loop. You can ofcourse collect the data returned by data.values() into an ArrayList or any collection of your choice to avoid the for loop.

You can use EntrySet if you need both key and value like below

for (Map.Entry<String, String> entry : data.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    // ...
}

CodePudding user response:

Try this:

  @PostMapping("/saveData")
  public ResponseEntity<String> saveData(@RequestBody Map<Integer, Object> data) {
    List<Object> values = new ArrayList<>();
    data.forEach(values::add);

    //Additonal code here, e.g. save

    return ResponseEntity.ok().build();
  }

@RequestBody Map<Integer, Object> ensures that indexes will always be Integers. Value type can be changed to String. If indexes are not int, 400 Bad Request will be returned. Indexes must be positive integers.

You can also user longer notation for adding elements to the list (might be more clear): data.forEach((key, value) -> values.add(key, value));


For this payload:
{
    "0": "3♥",
    "1": "5♣",
    "2": "4♣",
    "3": "9♥"
}

That's the outcome:

enter image description here

  • Related