scala中用json

文件结构:
{ "DenseFeature": [
     { "field":0,
     "Features":[
     “feature1”
      ]}
]
}
是这样的4层结构,不管用哪套api解析我都是崩溃的,想看看原来怎么拼成这么复杂的结果的。
用scala自带的json解析特别崩溃,因为从map里面拿出来是some类型,json对象还需要拿里面的对象才可以得到内容。
用google的gson库稍微。。。稍微好点

用gson解析:

val br = new BufferedReader(new InputStreamReader(this.getClass.getClassLoader.getResourceAsStream(modelName)))
val featureConf = readJson(br)
val jsonParser = new JsonParser()
val feaObj = jsonParser.parse(featureConf).asInstanceOf[JsonObject]
val denseArray = feaObj.get("DenseFeature").asInstanceOf[JsonArray].get(0).asInstanceOf[JsonObject]
val denseFea = denseArray.get("Features").asInstanceOf[JsonArray]
for(e <- denseFea.size()){
    print(denseFea.get(e)+"\n")
    }

gson的maven依赖:


   com.google.code.gson
   gson
   2.7

用scala自带json解析:

val br = new BufferedReader(new InputStreamReader(this.getClass.getClassLoader.getResourceAsStream(modelName)))
val featureConf = readJson(br)
val featureJson = JSON.parseRaw(featureConf).get.asInstanceOf[JSONObject]
val DenseFeatue = featureJson.obj.get("DenseFeature").get.asInstanceOf[JSONArray]
val DenseF = DenseFeatue.list(0).asInstanceOf[JSONObject].obj.get("Features").get.asInstanceOf[JSONArray].list
for( e <- DenseF){
   print(e.toString+"\n")
    }
连续的obj.get.asInstanceOf.list......搞不太清


你可能感兴趣的:(scala)