简体   繁体   English

如何在喷涂路由中将Java对象转换为Json

[英]How can I convert Java object to Json in spray routing

I would like to know if there is any way to return Java object as Json String inside spray routing. 我想知道是否有任何方法可以将Java对象作为Json String返回到内部喷涂路由中。

For now, I am converting my Java object (which is returned my UserActor) into Json using Jackson through a util class(JacksonUtil) created by me. 现在,我正在使用Jackson通过我创建的util类(JacksonUtil)将我的Java对象(返回我的UserActor)转换为Json。

Here is the code snippet for reference : 以下是供参考的代码段:

val route = {
    path("users" / Segment) { id =>
      parameterMap { params =>
        get {
          respondWithMediaType(MediaTypes.`text/plain`) {
            val resource: GetResource = new GetResource
            resource.searchCriteriaList.add(new SearchCriteria("userId", "=", Segment)) 
            logger.info("Request Received in new route: " + resource)
            onComplete(callUserActor(resource)) {
              case Success(ret: User) => {
                logger.info("Request complete. Success.")
                complete(JacksonUtil.toJson(ret))
              }
              case Failure(error) => {
                logger.info("Request complete. Failure. " + error)
                complete("Error: " + error)
              }
            }
          }
        }
      }
    } 
  }

def callUserActor(getResource: GetResource): Future[User] = {
    (userActor ? getResource).mapTo[User]
  }

GetResource is the class which take of query parameters. GetResource是获取查询参数的类。 For example if client hits GET /users/123, then GetResource will add a searchcriteria as userId = "123" 例如,如果客户端点击GET / users / 123,则GetResource将添加searchcriteria作为userId =“123”

I think you need to do it by yourself like by using Jackson or using LiftJson as per your needs and ease of Use. 我认为您需要自己做,例如使用Jackson或根据您的需求和易用性使用LiftJson Spray does not provide such feature by default as it does not have dependencies for this ! 默认情况下,Spray不提供此功能,因为它没有依赖性!

You can see the compile dependencies used by spray here : https://mvnrepository.com/artifact/io.spray/spray-routing_2.11/1.3.4 您可以在此处查看spray使用的编译依赖项: https//mvnrepository.com/artifact/io.spray/spray-routing_2.11/1.3.4

Screenshot : 截图:

在此输入图像描述

This should work for you, as simple as: 这应该适合你,简单如下:

class YourService(implicit val requestTimeout: Timeout)
extends HttpServiceActor with
   Json4sJacksonSupport {

  path("users" / Segment) { id =>
    parameterMap { params =>
      get {
        respondWithMediaType(MediaTypes.`text/plain`) {
          val user : Future[User] = Future { User("name", "90") }
          complete(user)
          }
        }
      }
    }  
  }

  implicit def json4sJacksonFormats: Formats = DefaultFormats.lossless
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM