Normal form submission vs. JSON

后端 未结 5 1989
生来不讨喜
生来不讨喜 2021-02-05 04:09

I see advantages of getting JSON response and formatting in client side but are there any advantages by using JSON for form submission compared to normal submission?

5条回答
  •  情歌与酒
    2021-02-05 04:59

    I am actually wrestling with the same problem. My use case requires that a potentially complex tree to be posted to the server. Some framework are able to decode two dimensional arrays as form attributes (Spring WebMVC is one I know of). Even so, this only helps you in the specific case when you are sending a nested array. The inherent nature of name-value-pair makes it unsuitable for transmitting a tree more than one level deep. In the past, I have used hacks like sending URL-encoded JSON as attribute value:

    val0=%7B%22name%22%3A%22value%22%7D&val1=something&val2=something+else
    

    However, this approach gets messy and difficult to debug when the object becomes more complex. In addition, many frameworks provide tools that automagically map JSON form post to objects (e.g.: Jackson for Java), it seems obtuse not to take advantage of these tools.

    So ultimately, the choice rests on the complexity of the object you are sending. If the object is limited to one level deep, use straight name-value-pair; if the object is complex and involves a deeply-nested tree, use JSON.

提交回复
热议问题