无形:找不到Coproduct映射的隐含

时间:2018-05-15 23:51:13

标签: scala shapeless circe

我有以下代码,它使用circe反序列化一个可以有两个形状的json(参见jsonPersonalDetails和jsonPersonalAddress的值)。当我尝试从SearchCriteria调用方法转换时,我得到:

  

错误:(38,26)找不到参数映射器的隐式值:shapeless.ops.coproduct.Mapper.Aux [com.example.circe.CirceShapeApp.transformer.type,com.example.circe.CirceShapeApp.SearchBy ,com.example.circe.CirceShapeApp.JsonPayload]

你能帮我弄清楚隐式映射器没有解决的原因吗?

谢谢!

    import io.circe.generic.auto._
    import io.circe.shapes._
    import io.circe.parser._
    import shapeless._
    import shapeless.ops.coproduct.Mapper

    object CirceShapeApp extends App {

      val jsonPersonalDetails = """{"searchCriteria": {"birthDate":"01-01-1980", "lastName":"John"}}""".stripMargin
      val jsonPersonalAddress = """{"searchCriteria": {"postalCode":"10776", "houseNumber":"34"}}""".stripMargin

      class SearchCriteria(val searchCriteria: SearchBy) {

        def transform(implicit mapper: Mapper.Aux[transformer.type, SearchBy, JsonPayload]) = {
          searchCriteria map transformer
        }
      }

      case class PersonalDetails(birthDate: String, lastName: String)

      case class PersonalAddress(postalCode: String, houseNumber: String)

      type SearchBy = PersonalDetails :+: PersonalAddress :+: CNil
      type JsonPayload = String :+: CNil

      object transformer extends Poly1 {

        implicit def casePersonalDetails = at[PersonalDetails](v => s"""{"bd": "${v.birthDate}", "ln":"${v.lastName}"}""")

        implicit def casePersonalAddress = at[PersonalAddress](v => s"""{"pc": "${v.postalCode}", "hn":"${v.houseNumber}"}""")

      }

      val result = decode[SearchCriteria](jsonPersonalDetails).right.get
      println(result.searchCriteria.map(transformer)) //WORKS
      println(result.transform) //DOESN'T WORK => COMPILATION ERROR
    }

1 个答案:

答案 0 :(得分:2)

我发现了问题。 JsonPayload 类型定义不正确。而不是:

type JsonPayload = String :+: CNil

我应该:

type JsonPayload = String :+: String :+: CNil