我需要将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的地图定义为一个类文件。
答案 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)