将JSON序列化为Scala案例类

时间:2015-04-28 18:13:13

标签: java json scala

我需要将JSON序列化为scala案例类。这不是关于JSON序列化的问题,而是关于scala中的类映射的问题。

JSON的例子:

{
  "id": 98433,
  "name": "Santa Cruz Bronson",
  "vendor": {
    "id": 344,
    "name": "Santa Cruz"
  },
  "category": {
    "id": 132,
    "name": "Bicycles"
  },
  "annotation": "The best downhill cycle",
  "description": "Rich text is here",
  "classification": {
    "id": 12,
    "name": "138-cycles"
  },
  "properties": [{
    "id": 84436,
    "group": {
      "id": 19433,
      "name": "Suspension"
    },
    "name": "Fork turn",
    "description": "Fork turn defines bike suspension",
    "value": "129mm"
  }, {
    "id": 84436,
    "group": {
      "id": 19433,
      "name": "Suspension"
    },
    "name": "Fork turn",
    "description": "Fork turn defines bike suspension",
    "value": "129mm"
  }, {
    "id": 84436,
    "group": {
      "id": 19433,
      "name": "Suspension"
    },
    "name": "Fork turn",
    "description": "Fork turn defines bike suspension",
    "value": "129mm"
  }, {
    "id": 84436,
    "group": {
      "id": 19433,
      "name": "Suspension"
    },
    "name": "Fork turn",
    "description": "Fork turn defines bike suspension",
    "value": "129mm"
  }],
  "isGroup": true
}

我知道如何为顶级地图构建案例类:

case class ProductDocument(id: Long, name: String, annotation: String, description: String, isGroup: String) extends DocumentMap {
    ...
}

但我不知道如何为供应商,类别,属性等构建值。

我想将此JSON的地图定义为一个类文件。

2 个答案:

答案 0 :(得分:3)

每个嵌套的json对象都应该被定义为它们自己的case类,例如:

case class Vendor(id: Long, name: String)
case class ProductDocument(id: Long, ..., vendor: Vendor)

properties将成为List案例类的Property

case class Property(id: Long, group: PropertyGroup, name: String, description: String, value: String)
case class PropertyGroup(id: Long, name: String)
case class ProductDocument(id: Long, ..., properties: List[Property])

这假定您使用的是json4s序列化。

答案 1 :(得分:0)

对于scala-json映射,您至少有两个选项:

Salat - 最初为Mongo提供类似ORM的功能,但也适用于JSON序列化(免责声明:我在Novus工作)

json4s - 请参阅“序列化”部分

好消息是,由于Scala案例类的结构已被很好地理解,因此通常不必在JSON字段和案例类字段之间定义“映射”。您只需编写案例类以匹配JSON文档的结构/字段,就像Arne Claassen勾画出的那样。