Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In Micronaut Controller parsing the post request using JSON object. I expect it to not include quotes, but it quotes in the database insert.

Posting like this:

curl -X POST --header "Content-Type: application/json" -d '{"bookid":3,"name":"C++"}'  http://localhost:8880/book/save

Saving like this:

String bookid=JSON?.bookid
  String name=JSON?.name
def b =bookService.save(bookid,name

in database It stores like this:

+--------+-------+
| bookid | name  |
+--------+-------+
| 3      | "C++" |
+--------+-------+

I expect book name just C++

Thanks SR

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
224 views
Welcome To Ask or Share your Answers For Others

1 Answer

I know i am a bit late but i've been searching for the solution for long and didnt find anything. After a lot of effort i found that sending jackson "Object" with "@BODY" is not helpful, when i changed the the type to "String" it worked for me.

Here is my Code

def save(@Body String JSON){

    def result = [:]
    ObjectMapper objectMapper = new ObjectMapper();

    //convert json string to object
    def obj = objectMapper.readValue(JSON, Course.class);
    println(obj)

    Course course = new Course(name: obj?.name, pre: obj?.pre,
            regno: obj?.regno, enrolled: obj?.enrolled)

    course.validate()
    if(course.hasErrors()){
        println("Error: "+course.errors)
        result.put("Error is: ",course.errors)
        return result;
    }

    course.save(flush:true,failOnError: true)

    result.put("Message","Successfully Created")
    result.put("Result",course)
    return HttpResponse.created(result)
}

Passing it to ObjectMapper and then converting it from JSON string to Java Object worked for me.

Json string that i passed is as follow:

{
 "name" : "Data Structures",
 "pre" : "Computer Programming",
 "regno" : "249",
 "enrolled" : "90"
}

Here is the storing of data before and after change in database:

+----+---------+------------------------+-------------------------------+----+
| id | version |        name      |   pre       |     regno        |enrolled |
+----+---------+------------------------+-------------------------------+----+
|  1 | 0 | "Computer Programming" | "Introduction to Programming"| "233"|"26"|
|  2 | 0 | Data Structures        | Computer Programming         |  249 | 90 |
+----+---------+------------------------+-------------------------------+----+

Hope the answer helps out anyone who is looking for alternate solution to above solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...