JSON is a concise format that is extremely popular for data exchange.
Most webservices these days consume JSON as input for processing instead of XML as it is lightweight(depenedent on domain)
Here is an example of consuming a json file uploaded via a web form in you web application using grails.
Grails as usual provides fantastic support for JSON parsing.
Parsing a JSON input and creating domain objects out this is very easy with grails.
I have a domain object like this
class Message {
String name
String content
static constraints = {
name(nullable:false)
content(nullable:false)
}
}
Here is a sample JSON input file that can be used for creating multiple domain objects
[
{"name":"ann","content":"What a Wonderful World"},
{"name":"nandhu","content":"Wonderful World"},
]
Note that JSON representation is very simple.
Key,Value pairs separated by ":" for each property and enclosed in {} constitute one object.
Objects can be separated by comma and enclosed with [] to constitute an array of like objects.
In order to upload the JSON file we would need a multipart form upload gsp as shown below
//form multipart upload code
<div>
<g:form method="post" action="postRest" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</g:form>
</div>
This form does a post to action called "postRest" on the same controller.
A different controller can be used by using controller="name" property in addition
Now finally you need to add the controller action.
There you have to get the JSON representation first.
Then you create a domain object and fill data into it from JSON representation.
Finally you save this object.
Make sure you check the newly saved object to ensure there arent any errors.
def postRest = {
println request.getFile("file").inputStream.text
def jsonArray = JSON.parse(request.getFile("file").getInputStream(),"UTF-8")
println "jsonArray=${jsonArray}"
jsonArray.each{
println it
Message m = new Message()
bindData(m, it)
m.save(flush:true)
if(m.errors) {
m.errors.each{println it}
}
}
}
In the next post I will blog on how to expose this as a webservice.
No comments:
Post a Comment