Home > Back-end >  How do I return a JSON object with duplicate keys in Spring Boot?
How do I return a JSON object with duplicate keys in Spring Boot?

Time:12-21

I'm running into an issue I don't know how to resolve. I need to return a JSON object that has duplicate keys.

I understand this is perfectly valid according to the JSON specification. See ecma-404, page 6 that reads:

The JSON syntax does not impose any restrictions on the strings used as names, does not require that name strings be unique...

I need to return this:

{
  "id":"1401",
  "sku":"C18-25",
  "sku":"A15-70"
}

I've been using a typical rest method in Spring Boot:

@GetMapping("/{id}")
@ResponseBody
public ResponseEntity<?> getProduct(@PathVariable String id) {
  Map<String, String> r = new HashMap<>();
  r.put("id", "1401");
  r.put("sku", "C18-25");
  r.put("sku", "A15-70");
  return new ResponseEntity<Map<String, String>>(r, HttpStatus.OK);
}

But it only keeps the last entry:

{
  "id":"1401",
  "sku":"A15-70"
}

How can I return multiple entries with the same name?

CodePudding user response:

A HashMap only allows unique key values, so there is no way for you to use HashMap for this purpose. Also while you are correct, you can use duplicate key values in a JSON body, it is not recommended. Why not make sku an array like this?

"sku":["A15-70","C18-25"]

CodePudding user response:

While creating map create like this

Map<String, List<String>> map = new HashMap<>();

while putting existing key in Map check using containsKey() method and put duplicate value in List of key

you will get result like this

{ "id":"1401", "sku":["A15-70","C18-25"] }

CodePudding user response:

You can just return a string with response entity.

String response = "{\n" 
"  \"id\":\"1401\",\n" 
"  \"sku\":\"C18-25\",\n" 
"  \"sku\":\"A15-70\"\n" 
"}";
return new ResponseEntity<String>(response, HttpStatus.OK);

It is not pretty, but it is supported by Spring and will get the job done.

  • Related