挺费劲的,java和scala的返回方式为了统一,需要封装scala的返回方式 ,需要一个listmap,但是如果是java可以直接将listMap放入json中就可以了,但是scala不行,我们也不能将对象直接装成jsonstring,这样的话,我们在放入json后,会自动加上转义字符,可以使用listbuffer 然后转array
package flinkonkafka
import net.minidev.json.JSONObject
import net.minidev.json.parser.JSONParser
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature
import scala.beans.BeanProperty
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
import scala.collection.JavaConversions.bufferAsJavaList
/***
* @Author BaronND
* @Description 从kafka上获取的json解析
* @Date 2020/6/11
* @Param
* @return
**/
class RequestJson{}
case class result(@BeanProperty code:String,@BeanProperty value:String)
object RequestJson{
def main(args: Array[String]): Unit = {
var resultMap = Map("CF402" -> "-0.037855187404791296", "CF327" -> "0.06558579235761422", "CF401" -> "-0.030836201749878455", "CF33" -> "-0.008973041330299265")
var a=getArrayObj(resultMap)
var b=getArrayObjs(resultMap)
println(a)
println(b)
}
//计算参数
def getStringJson(s: String): mutable.Map[String, Object] = {
val jsonobj = JSON.parseObject(s)
val jsonParm = jsonobj.getJSONObject("parameter")
var parameter=jsonToMap(jsonParm.toString)//请求参数封装
JSON.toJSONString(parameter, SerializerFeature.WriteMapNullValue)
parameter
}
//返回原来的json
def callBackJson(requestJSON:String,handleTs:Long,map:Map[String,String],message:String) ={
import com.alibaba.fastjson.JSONObject
val js = JSON.parseObject(requestJSON)
val jsonObj :JSONObject= new JSONObject()
var rs=mutable.Map[String, Object]()
var data=getArrayObj(map)
val jsonResult = js.getJSONObject("result")
jsonResult.put("data",data)
jsonResult.put("message",message)
js.put("result", jsonResult)
js.put("handleTs",handleTs)
js
}
//获取计算参数
def getCallBackUrl(s: String):String = {
import com.alibaba.fastjson.JSON
val jsonobj = JSON.parseObject(s)
val jsonParm = jsonobj.getString("callbackUrl")
jsonParm
}
//对应的json转map
def jsonToMap(svdInfo: String) = {
val parserJson = new JSONParser()
val jsonObj: JSONObject = parserJson.parse(svdInfo).asInstanceOf[JSONObject]
val jsonKey = jsonObj.keySet()
val iter = jsonKey.iterator()
val map: mutable.HashMap[String, Object] = new mutable.HashMap[String, Object]()
while (iter.hasNext) {
val instance = iter.next()
val value = jsonObj.get(instance).toString
map.put(instance, value)
}
map
}
//将获取的map对象封装成对应的array[result] 结果:[Lflinkonkafka.result;@bd8db5a
def getArrayObj(map:Map[String,String])={
var ll=new ListBuffer[result]
// val array = ArrayBuffer[result]()
map.map(m => {
var r= new result(m._1,m._2)
// array.add(r)
ll.add(r)
})
ll.toArray
}
//将获取的map对象封装成对应的array[result]:结果:ArrayBuffer(result(CF402,-0.037855187404791296), result(CF327,0.06558579235761422))
def getArrayObjs(map:Map[String,String])={
val array = ArrayBuffer[result]()
map.map(m => {
var r= new result(m._1,m._2)
array.add(r)
})
array
}
}