简体   繁体   English

如何将 None 字段从案例类正确转换为 JSON

[英]How can i convert None field from case class to JSON correctly

I have this case class我有这个案例课

case class Example(
      exId: String,
      exDes: Option[String] = None)

and I try to convert我尝试转换

Example(exId = 1)

to JSON (example.asJson from io.circe) I actually got到 JSON(来自 io.circe 的 example.asJson)我实际上得到了

{
"exId" : "1"
"exDes": null
}

But i expected但我预计

{
    "exId" : "1"
}

is there anyway to convert like i expected with io.circe ?有没有像我预期的那样使用 io.circe 进行转换?

Just use dropNullValues , as it Scala Docs states:只需使用dropNullValues ,因为它 Scala Docs 状态:

Drop the entries with a null value if this is an object.如果这是一个对象,则删除具有空值的条目。

Your example looks then:你的例子看起来像:

Example(exId = "1").asJson.dropNullValues

And the result is as you wanted:结果如您所愿:

{
  "exId" : "1"
}

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

相关问题 如何将案例 class 转换为 lift-json 作业 class? - How can I convert a case class to a lift-json jobject class? 当字段是 scala 关键字时,如何自动将 JSON 映射到 case 类? - How can I automatically map JSON to a case class when a field is a scala keyword? 如何将JSON响应的密钥从snakecase转换为camel case? - How can I convert my JSON response's key from snakecase to camel case? 如何构造枚举不区分大小写? 这样当我将 json 转换为类对象时,它看不到对象的情况 - how to construct enum case insensitive? so that when i convert a json to class object, it do not see the case of object 将Scala案例类转换为json - Convert scala case class to json 将 json 字符串从给定的 json 字符串和 case 类类型转换为 case 类对象 - convert json string to case class object from given json string and type of case class 我应该如何将 JSON 有效载荷的大小写转换为小驼峰大小写? - How should I convert the case of a JSON payload to lower camel case? 如何编写自定义Provider类以将JSON转换为布尔值? - How can I write a custom Provider class to convert JSON to Boolean? 如何正确读取 url 中的 JSON 数组数据 - how can i read JSON array data from url correctly 如何使用Json.reads将JSON反序列化为具有可选构造函数参数的case类 - How can I use Json.reads to deserialize JSON into a case class with optional constructor parameters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM