我有一个要求,即传入的JSON对象很复杂,并且大多数是嵌套的:
"users": {
"utype": "PERSON",
"language":"en_FR",
"credentials": [
{
"handle": "xyz@abc.com",
"password": "123456",
"handle_type": "EMAIL"
}
],
"person_details": {
"primary": "true",
"names": [
{
"name_type": "OFFICIAL",
"title": "MR",
"given": "abc",
"family": "zat",
"middle": "pqs",
"suffix":"anathan"
}
],
"addresses": [
{
"ad_type": "HOME",
"line1": "Residential 2211 North 1st Street",
"line2": "Bldg 17",
"city": "test",
"county": "Shefield",
"state" : "NY",
"country_code": "xx",
"postal_code": "95131"
}
]
}
}
为了解析这个结构,我使用下面的Case Classes
case class PersonUser (
user_type:String,
language_code:String,
credentials:List[Credential],
person_details:PersonDetails
)
case class Credential(handle:String, password:String,handle_type:String)
case class PersonDetails(
primary_user:Boolean,
names: List[Name],
addresses:List[Address]
)
case class Name(
name_type: String,
title: String,
given: String,
family: String,
middle: String,
suffix:String
)
case class Address(
address_type: String,
line1: String,
line2: String,
city: String,
county: String,
state : String,
country_code: String,
postal_code: String
)
要将JSON结构转换为Scala,我使用了JSON Inception:
implicit val testReads = Json.reads[PersonUser]
此外,我必须在子类中指定类似的读取含义 - 凭据,PersonDetails,名称和地址。在下面给出了这样的例子:
case class Credential(handle:String, password:String,handle_type:String)
object Credential{
implicit val reads = Json.reads[Credential]
}
现在问题是,如果我的JSON结构非常庞大,有很多子结构,那么我需要定义一些Scala案例类。为每个案例类定义伴随对象和隐式读取将非常麻烦(例如:如果我有8个案例类来完全表示JSON结构,我将不得不定义8个伴随对象)。有没有办法避免这项额外的工作?
答案 0 :(得分:2)
这个问题已经回答了,但我想我会解释为什么会这样。
答案 1 :(得分:1)
不,没有办法避免为你想要(de)序列化的每个类定义一个Format
实例。