PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How to send Json array from ajax to spring Controller?

 July 23, 2022     ajax, javascript, json, spring, spring-boot     No comments   

Issue

I have an html table like below from which I convert the data to a json form and send via ajax to a spring controller. In the spring controller I used @RequestParam Map<String, String> to get the values, but I got the whole json string as the only key. Using modelAttribute I can achieve this, but I have different scenarios so I cannot use the model class so I also want these column headers with their values.

<table>
<thead>
<tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
    <td>A1</td>
    <td>A2</td>
    <td></td>
</tr>
<tr>
    <td>B1</td>
    <td>B2</td>
    <td>B3</td>
</tr>
<tr>
    <td>C1</td>
    <td></td>
    <td>C3</td>
</tr>
</tbody>

I convert the html table data to json and send via ajax. -

  [
    {
    "Column 1": "A1",
    "Column 2": "A2",
    "Column 3": ""
    },
   {
    "Column 1": "B1",
    "Column 2": "B2",
    "Column 3": "B3"
   },
   {
    "Column 1": "C1",
    "Column 2": "",
    "Column 3": "C3"
   }
  ]

ajax code -

$.ajax({
        type: "POST",
        //contentType : 'application/json; charset=utf-8',
        //dataType : 'json',
        url: "/gDirecotry/" + id,
        data: JSON.stringify(rows),
        success: function (result) {
            console.log(result);
        }
    });

Spring controller code -

  @RequestMapping(value = "/gDirecotry/{id}", method = RequestMethod.POST)
  public @ResponseBody ModelAndView 
      getSearchUserProfiles(@PathVariable("id") String id,
                                 @RequestParam Map<String, String> 
   attributeMap) throws IOException {

return new ModelAndView("redirect:/home");
  }

I want to map the json data to map<string,string>, how could I acheive this?

OUTPUT : - I got this whole string as the only key without value.

[{"Column 1":"A1","Column 2":"A2","Column 3":""},{"Column 1":"B1","Column 
2":"B2","Column 3":"B3"},{"Column 1":"C1","Column 2":"","Column 3":"C3"}]

Solution

Change:

@RequestParam Map<String, String> attributeMap

To

@RequestBody List<Map<String, String>> attributeMap

Your JSON payload is an array of objects.



Answered By - MichaƂ Ziober
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing