Created
April 6, 2018 07:13
-
-
Save dbtsai/2c22770a812aa1f5732e2e7a408e0dec to your computer and use it in GitHub Desktop.
testing json stream parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val jsonTxt = | |
""" | |
|{ | |
| "name": "Tom", | |
| "age": 25, | |
| "address": ["Poland", "5th avenue"] | |
|} | |
|""".stripMargin | |
/** | |
* Gson | |
*/ | |
import com.google.gson.GsonBuilder | |
val map: java.util.Map[String, Object] = | |
new GsonBuilder().create.fromJson(jsonTxt, classOf[java.util.Map[String, Object]]) | |
/** | |
* Streaming Gson | |
*/ | |
import com.google.gson.stream.JsonReader | |
val reader = new java.io.StringReader(jsonTxt) | |
val jsonStreamReader = new JsonReader(reader) | |
jsonStreamReader.beginObject() | |
while (jsonStreamReader.hasNext) { | |
val name = jsonStreamReader.nextName() | |
name match { | |
case "address" => | |
jsonStreamReader.beginArray() | |
while (jsonStreamReader.hasNext) { | |
println(jsonStreamReader.nextString()) | |
} | |
jsonStreamReader.endArray() | |
case _ => jsonStreamReader.skipValue() | |
} | |
} | |
jsonStreamReader.endObject() | |
jsonStreamReader.close() | |
/** | |
* Streaming Jackson | |
*/ | |
import org.codehaus.jackson.JsonFactory | |
import org.codehaus.jackson.JsonToken | |
val jsonFactory = new JsonFactory() | |
val jParser = jsonFactory.createJsonParser(jsonTxt) | |
while (jParser.nextToken() != JsonToken.END_OBJECT) { | |
val name = jParser.getCurrentName | |
name match { | |
case "address" => | |
jParser.nextToken() | |
while (jParser.nextToken() != JsonToken.END_ARRAY) { | |
println(jParser.getText) | |
} | |
case _ => jParser.skipChildren() | |
} | |
} | |
jParser.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment