Micronaut JSON post strip the Quotes

浪子不回头ぞ 提交于 2019-12-25 18:37:37

问题


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


回答1:


You haven't provided enough information about your project to know what is going on but the project at https://github.com/jeffbrown/sfgroupsjsonbinding/tree/master demonstrates how the built in binding stuff works. See the README.md file there.

https://github.com/jeffbrown/sfgroupsjsonbinding/blob/3ff4e8b39ba5fda9956ebfc67cd0b9e5d940b8f2/src/main/groovy/sfgroupsjsonbinding/BookController.groovy

package sfgroupsjsonbinding

import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Post

@Controller('/book')
class BookController {

    private PersonService personService

    BookController(PersonService personService) {
        this.personService = personService
    }

    @Get('/')
    List<Person> list() {
        personService.list()
    }

    @Post('/')
    Person save(Person person) {
        personService.save person
    }

    @Get('/{id}')
    Person get(long id) {
        personService.get id
    }
}

Interacting With The App

 $ curl -H "Content-Type: application/json" -d '{"name":"Jeff"}' http://localhost:8080/book
{"name":"Jeff","id":1}
 $ 
 $ curl -H "Content-Type: application/json" -d '{"name":"Jake"}' http://localhost:8080/book
{"name":"Jake","id":2}
 $ 
 $ curl -H "Content-Type: application/json" -d '{"name":"Zack"}' http://localhost:8080/book
{"name":"Zack","id":3}
 $ 
 $ curl http://localhost:8080/book
[{"name":"Jeff","id":1},{"name":"Jake","id":2},{"name":"Zack","id":3}]
 $ 
 $ curl http://localhost:8080/book/1
{"name":"Jeff","id":1}
 $ 
 $ curl http://localhost:8080/book/2
{"name":"Jake","id":2}
 $ 
 $ curl http://localhost:8080/book/3
{"name":"Zack","id":3}
 $ 



回答2:


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.




回答3:


It seems my command class extending some other class was causing some issues which meant nothing worked. At the moment it does work and is really a working alternative to what Zaryab baloch had suggested above.

package gateway.command.controller;


import com.fasterxml.jackson.annotation.JsonProperty;
import gateway.command.event.commands.HotelSaveCommand;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.codec.MediaTypeCodecRegistry;
import io.micronaut.jackson.codec.JsonMediaTypeCodec;
import lombok.extern.slf4j.Slf4j;

import javax.inject.Inject;

@Slf4j
@Controller("/")
public class GatewayController  {

    @Inject
    protected MediaTypeCodecRegistry mediaTypeCodecRegistry;

    /**
     *
     * @param topic
     * @param eventType using the jsonProperty we actually extract eventType from the @Body string JSON String
     *                  The 3rd input is actual form. we post /hotel and json content there isn't actually 3 parameters
     *                  provided
     * @param
     * @return
     */
    @Post(uri = "/{topic}", consumes = MediaType.APPLICATION_JSON)
    public HttpResponse process(String topic, @JsonProperty("eventType") String eventType, @Body String formInput)  {

        JsonMediaTypeCodec mediaTypeCodec = (JsonMediaTypeCodec) mediaTypeCodecRegistry.findCodec(MediaType.APPLICATION_JSON_TYPE)
                .orElseThrow(() -> new IllegalStateException("No JSON codec found"));

        HotelSaveCommand command =  mediaTypeCodec.decode(HotelSaveCommand.class,formInput);
        if (command!=null) {
            System.out.println(command +" "+ command.getName());
        }
        //eventPublisher.publish(topic,);
        return HttpResponse.accepted();
    }

}


来源:https://stackoverflow.com/questions/54000199/micronaut-json-post-strip-the-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!