1

私の場合、同じ json フィールドの異なるデータ型が存在する可能性があります。例:

"need_exp":1500

また

"need_exp":"-"

このケースをどのように処理しますか? カスタムエンコーダーで処理または使用できることはわかっていますがparse、これは非常に複雑な json テキストです。デコーダー全体を書き換えずに解決する方法はありますか (たとえば、すべてをフィールド内に変換するようにデコーダーに「指示」するだけです)。 ?IntStringneed_exp

4

2 に答える 2

1

私の解決策は、カスタム デコーダーを使用することです。JSON の一部を書き直せば問題ありません。

たとえば、単純な JSON があります。

{  
   /*many fields*/
   "hotList":[/* ... many lists inside*/],
   "list":[ {/*... many fields*/
         "level_info":{  
            "current_exp":11463,
            "current_level":5,
            "current_min":10800,
            "next_exp":28800 //there is the problem
         },
         "sex":"\u4fdd\u5bc6"},/*...many lists*/]
}

この場合、JSON エンコーダー全体を書き直す必要はなく、次のカスタム エンコーダーを作成するだけですlevel_info

implicit val decodeUserLevel: Decoder[UserLevel] = (c: HCursor) => for
{
    current_exp <- c.downField("current_exp").as[Int]
    current_level <- c.downField("current_level").as[Int]
    current_min <- c.downField("current_min").as[Int]
    next_exp <- c.downField("next_exp").withFocus(_.mapString
    {
        case """-""" => "-1"
        case default => default
    }).as[Int]
} yield
{
    UserLevel(current_exp, current_level, current_min, next_exp)
}

そしてそれはうまくいきました。

于 2017-08-16T02:42:08.107 に答える