1
1
package com .github .tashoyan .telecom .spark
2
2
3
+ import java .io .StringWriter
3
4
import java .sql .Timestamp
4
5
import java .time .{ZoneId , ZonedDateTime }
5
6
7
+ import com .fasterxml .jackson .databind .ObjectMapper
8
+ import com .fasterxml .jackson .module .scala .DefaultScalaModule
6
9
import com .github .tashoyan .telecom .spark .DataFrames .RichDataFrame
7
10
import com .github .tashoyan .telecom .test .SparkTestHarness
8
11
import org .apache .spark .sql .types ._
9
12
import org .scalatest .FunSuite
10
13
11
- import scala .util .parsing .json .{JSON , JSONObject }
12
-
13
14
class DataFramesTest extends FunSuite with SparkTestHarness {
14
15
15
16
test(" withJsonColumn" ) {
@@ -31,9 +32,8 @@ class DataFramesTest extends FunSuite with SparkTestHarness {
31
32
val jsonStr = resultDf.select(" json_column" )
32
33
.as[String ]
33
34
.head()
34
- val parsedResult = JSON .parseFull(jsonStr)
35
- .get
36
- .asInstanceOf [Map [String , Any ]]
35
+
36
+ val parsedResult = jsonToMap(jsonStr)
37
37
assert(parsedResult(" int_column" ) === 1 )
38
38
assert(parsedResult(" long_column" ) === 10L )
39
39
assert(parsedResult(" double_column" ) === 2.5 )
@@ -56,15 +56,14 @@ class DataFramesTest extends FunSuite with SparkTestHarness {
56
56
StructField (" string_column" , StringType ),
57
57
StructField (" timestamp_column" , TimestampType )
58
58
))
59
- val sampleStr = Map [String , Any ](
59
+ val sample = Map [String , Any ](
60
60
" int_column" -> 1 ,
61
61
" long_column" -> 10L ,
62
62
" double_column" -> 2.5 ,
63
63
" string_column" -> " one" ,
64
64
" timestamp_column" -> " 1970-01-01T00:00:01.001Z"
65
65
)
66
- val sampleJson = JSONObject (sampleStr)
67
- .toString()
66
+ val sampleJson = mapToJson(sample)
68
67
69
68
val sampleDf = Seq (
70
69
(" something" , sampleJson)
@@ -85,4 +84,19 @@ class DataFramesTest extends FunSuite with SparkTestHarness {
85
84
assert(result.getAs[Timestamp ](" timestamp_column" ) === new Timestamp (1001L ))
86
85
}
87
86
87
+ private val mapper : ObjectMapper = {
88
+ new ObjectMapper ()
89
+ .registerModule(DefaultScalaModule )
90
+ }
91
+
92
+ private def jsonToMap (json : String ): Map [String , Any ] = {
93
+ mapper.readValue(json, classOf [Map [String , Any ]])
94
+ }
95
+
96
+ private def mapToJson (map : Map [String , Any ]): String = {
97
+ val out = new StringWriter ()
98
+ mapper.writeValue(out, map)
99
+ out.toString
100
+ }
101
+
88
102
}
0 commit comments