0

在 Micronaut 控制器中,使用 JSON 对象解析发布请求。我希望它不包含引号,但它会在数据库插入中引用。

像这样发帖:

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

像这样保存:

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

在数据库中它是这样存储的:

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

我只希望书名C++

谢谢

4

3 回答 3

3

我知道我来晚了,但我一直在寻找解决方案,但没有找到任何东西。经过大量努力,我发现发送带有“@BODY”的杰克逊“对象”没有帮助,当我将类型更改为“字符串”时,它对我有用。

这是我的代码

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)
}

将它传递给 ObjectMapper,然后将它从 JSON 字符串转换为 Java 对象对我有用。

我传递的Json字符串如下:

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

这是数据库更改前后数据的存储:

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

希望答案可以帮助任何正在寻找上述解决方案的替代解决方案的人。

于 2019-02-27T12:22:21.823 回答
0

似乎我的命令类扩展了其他一些类导致了一些问题,这意味着没有任何效果。目前它确实有效,并且确实是 Zaryab baloch 上述建议的有效替代方案。

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();
    }

}
于 2019-06-17T16:15:31.340 回答
0

您没有提供有关您的项目的足够信息来了解正在发生的事情,但https://github.com/jeffbrown/sfgroupsjsonbinding/tree/master上的项目演示了内置绑定的工作原理。请参阅那里的 README.md 文件。

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
    }
}

与应用程序交互

 $ 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}
 $ 
于 2019-01-02T02:56:41.353 回答