[英]json4s response to case class
I am getting this json response, how to create Scala Case Class for the page_views ?? 我收到此json响应,如何为page_views创建Scala Case类?
"page_views": {
"2015-12-30T21:30:00+05:30": 4,
"2016-01-08T15:30:00+05:30": 25,
"2016-01-13T11:30:00+05:30": 9,
"2016-01-13T12:30:00+05:30": 8,
"2016-01-14T10:30:00+05:30": 21,
"2016-01-21T12:30:00+05:30": 19,
"2016-01-21T17:30:00+05:30": 4,
"2016-01-22T17:30:00+05:30": 2,
"2016-02-02T10:30:00+05:30": 14,
"2016-02-24T12:30:00+05:30": 11,
"2016-02-26T09:30:00+05:30": 12
},
First define what case class you want. 首先定义所需的案例类。 Let's say it's something like
case class PageView(date:myDateType,numberViews:Long)
. 比方说
case class PageView(date:myDateType,numberViews:Long)
。 Then you don't fall in the basic case where the json you receive has the fields date
and numberViews
explicitly written, eg {"date":"xxx","numberViews":123}
. 那么,您就不会陷入接收到的json具有显式编写的
date
和numberViews
字段的基本情况,例如{"date":"xxx","numberViews":123}
。 So using json4s it won't be enough to create a case class and let it do the rest, you will have to write a custom (de)serializer (they have an example here , search 'Serializer' on the page). 因此,使用json4s不足以创建一个case类并让其完成其余的工作,您将不得不编写一个自定义(de)序列化器( 此处有一个示例,在页面上搜索'Serializer')。
After many tries , I was able to make it work. 经过多次尝试,我得以使其工作。 I used a
Map
to bind to the JSON fields. 我使用
Map
绑定到JSON字段。
case class Test(page_views: Map[String, Int])
you may follow up this tutorial that covers how to parse json strings to your model. 您可以继续阅读本教程 , 该教程涵盖如何将json字符串解析为模型。 It also covers some usual transformations you may need to apply to convert from the json to your case class
它还涵盖了一些常见的转换,您可能需要应用这些转换才能将json转换为case类。
but your case is kinda weird, shouldn't page_views contain/be an array? 但您的情况有点奇怪,page_views是否不应该包含/是数组? how can you process the page_views json object if you don't know which fields are in it?
如果您不知道其中包含哪些字段,如何处理page_views json对象?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.