2016-12-23 4 views
2

にJson4Sのための移行私は、次のキルケコードキルケ

import io.circe._ 
import io.circe.syntax._ 
import io.circe.generic.auto._ 
import io.circe.parser.decode 
def unmarshall[T <: AnyRef](input: String)(implicit m: Manifest[T]) : T ={ 
    decode[T](input).right.get 
} 
def marshall[T <: AnyRef](input: T)(implicit m: Manifest[T]) : String = { 
    input.asJson.toString 
} 

を書かれている。しかし、私はエラー

を取得

import org.json4s._ 
def jsonRead[T <: AnyRef](input: String)(implicit m: Manifest[T]): T = { 
    Try(read[T](input)).get 
} 

def jsonWrite[T <: AnyRef](input: T)(implicit m: Manifest[T]): String = { 
    write[T](input).toString 
} 

をコンパイルし、正常に動作json4sで書かれた次のコードを持っています

Error:(27, 16) could not find implicit value for parameter decoder: io.circe.Decoder[T] decode[T](json).right.get 
Error:(27, 16) not enough arguments for method decode: (implicit decoder: io.circe.Decoder[T])Either[io.circe.Error,T]. Unspecified value parameter decoder. decode[T](json).right.get 
Error:(30, 11) could not find implicit value for parameter encoder: io.circe.Encoder[T] obj.asJson.toString 
Error:(30, 11) not enough arguments for method asJson: (implicit encoder: io.circe.Encoder[T])io.circe.Json. Unspecified value parameter encoder. obj.asJson.toString 

答えて

5

json4sおよびcirceは、異なるそれはあなたが同じテクニックを使うことができない理由です。 json4sreadでは、Jsonから値を抽出するためにマニフェストが必要ですが、circeには、型クラスDecoderのインスタンスが必要です。あなたはあなたの例ではcirceを使用したい場合は、私は両方の実装を読むことをお勧めの違いを理解するために

def unmarshall[T <: AnyRef](input: String)(implicit d: Decoder[T]) : T = { 
    decode[T](input).right.get 
} 
def marshall[T <: AnyRef](input: T)(implicit e: Encoder[T]) : String = { 
    input.asJson.toString 
} 

のようなものを書く必要があり、彼らは2つのライブラリは、彼らが何を行うかを理解することは非常に便利です。 json4sネイティブのreadとcirce decodeのシグネチャにはすでに違いがあります。ここでは、2つの図書館の基本的な違いを説明するために、署名の重要な部分をコピーします。 readネイティブjson4sの署名は、「あなたはそれのためのScalaのマニフェストを提供する場合、私はどのようなタイプのAに文字列を変換することができます」と解釈することができ

def read[A](input: String)(implicit mf: Manifest[A]): A 

です。 Manifestは反射のために使用されるScala特性なので、readは反射を使用すると推定できます。

キルケdecodeの署名

は異なっている:「私はあなたがそれのためにキルケデコードインスタンスを提供する場合、A型に文字列を変換しようとすることができます」と読むことができます

def decode[A](input: String)(implicit d: Decoder[A]): Either[Error, A] 

Decoder typeclassは、システムに、Aの値をjsonからどのようにデコードするかを伝えるだけです。