【问题标题】:Customized Scala deserializer for all kinds of JValues为各种 JValue 定制的 Scala 反序列化器
【发布时间】:2017-05-26 09:48:09
【问题描述】:

我的问题:我有一个我不知道确切结构的 Json 结构。例如,它可能是以下内容:

val json = JObject(List(
      ("text1", JString("testting <html>")),
      ("text2", JString("Test <script>script</script>")),
      ("text3", JObject(List(
        ("data", JObject(List(
          ("text", JString("Testing if <html> tags disappear </html>")),
          ("text2", JInt(2))
        )))
      ))
      )
    ))

我需要在 Scala 中编写一个自定义的反序列化器(使用 json4s),它遍历 JValue(例如,上面的那个)并从 JValue 结构中的所有 JStrings 中删除所有 html 标记,然后提取最终的 Jvalue 结构到我的 Scala 案例课程。我尝试了几种解决方案都没有成功。

请帮忙。

【问题讨论】:

    标签: json scala serialization deserialization json4s


    【解决方案1】:
    @ val regex = """<[^>]*>""".r
    regex: util.matching.Regex = <[^>]*>
    @ json transformField {
      case JField(k,JString(t)) => (k, JString(regex replaceAllIn(t,"")))
      }
    res47: JValue = JObject(List((text1,JString(testting )), (text2,JString(Test script)), (text3,JObject(List((data,JObject(List((text,JString(Testing if  tags disappear )), (text2,JInt(2))))))))))
    

    其实很简单,只要使用json4s提供的transformField方法,使用合适的正则即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-05
      • 2013-01-21
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      相关资源
      最近更新 更多