简体   繁体   English

Argonaut-在自定义解码器中返回错误

[英]Argonaut - Returning an error in a custom decoder

I'm trying to implement an Argonaut JSON decoder instance that converts JSON strings to instances of my enum QuestionType . 我正在尝试实现一个Argonaut JSON解码器实例,该实例将JSON字符串转换为我的枚举QuestionType实例。 The problem is that if the string isn't a valid, the returned DecodeResult should be an error, and I'm not sure how to do that. 问题是,如果字符串无效,则返回的DecodeResult应该是错误,并且我不确定如何执行此操作。

My code currently looks like this: 我的代码当前如下所示:

implicit def QuestionTypeDecodeJson: DecodeJson[QuestionType] = {
    DecodeJson(c => for {
      typeName <- c.as[String]
      questionType = QuestionType.fromString(typeName).get
    } yield questionType)
  }

QuestionType.fromString(typeName) returns an Option . QuestionType.fromString(typeName)返回一个Option Ideally, instead of using get , I would like to convert the Option to a DecodeResult , with either the contents of the Option, or an error state if it's None . 理想情况下,我不想使用get ,而是将Option转换为DecodeResult ,其中包含Option的内容,或者如果错误状态为None则返回错误状态。

I could use the constructor of DecodeResult , but to be honest the signature of that is quite confusing to me (I'm new to scala). 我可以使用DecodeResult的构造DecodeResult ,但是老实说,它的签名让我很困惑(我是scala的新手)。 It seems that it requires a CursorHistory object, and I'm not sure what I'm supposed to pass in there. 似乎它需要一个CursorHistory对象,并且我不确定应该在其中传递什么。

DecodeResult object has an 'ok' and a 'fail' method. DecodeResult对象具有“确定”和“失败”方法。

implicit def QuestionTypeDecodeJson: DecodeJson[QuestionType] = {
    DecodeJson(c => for {
      typeName <- c.as[String]
      questionType = DecodeResult.ok(QuestionType.fromString(typeName))
    } yield questionType)
}

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

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