zoukankan      html  css  js  c++  java
  • Scala中json格式、字符串、map相互转换

    像map一样的json直接存值:

    import org.json.JSONObject

    def main(args: Array[String]): Unit = {

    val jsonObj :JSONObject= new JSONObject()
    jsonObj.put("zxtotal", "1")
    jsonObj.put("zxtota1l", "11")
    println(jsonObj)
    }

    json对象转换为json字符串:

    import org.json4s.{Formats,NoTypeHints}
    import org.json4s.jackson.Serialization
    import org.json4s.jackson.Serialization.write
    
    
    case class userLableLike(id:String,pos:Float,neg:Float,seg:Double)
      def userLable2Str(data:userLableLike): String ={
        // 需要添加隐式转换
        implicit val formats:AnyRef with Formats = Serialization.formats(NoTypeHints)
        // 由scala对象转换为Json字符串
        val dstr = write(data)
        dstr
      }
    
    val v1 = userLableLike("1",100,100,0.5)
    println(userLable2Str(v1))
    // "{id: 1, pos: 100, neg: 100, seg: 0.5}"
    

     

    json字符串转换成map:

    import scala.util.parsing.json.JSON
    
    // 把json格式的字符串转换成map格式,(id:String,pos:Float,neg:Float,seg:Double)
      def str2map(vstr:String): collection.immutable.Map[String, Any] ={
        val vSome = JSON.parseFull(vstr)
    //    println(vSome,manOf(vSome)) //(Map(id -> 1, pos -> 100.0, neg -> 100.0, seg -> 0.5),Any)
        // 转换类型
        var vmap = vSome match {
          case Some(map:collection.immutable.Map[String, Any]) => map
        }
    //    println(vmap("id"),manOf(vmap)) //(1,scala.collection.immutable.Map[java.lang.String, Any])
        vmap
      }
    //注意用可变集合collection.mutable.Map[String, Any] ,行不通
    
    //查看数据类型方法-manOf(data)
      def manOf[T:Manifest](t:T):Manifest[T]=manifest[T]

    import com.alibaba.fastjson.{JSON, JSONException, JSONObject}

    val json: JSONObject = JSON.parseObject(line)
    println(json.get("id").toString)

    pom.xml
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
    </dependency>
  • 相关阅读:
    jQuery禁用或启用
    ASP.NET MVC一次删除多笔记录
    在你的ASP.NET MVC中使用查找功能
    Get radio selected value
    绑定一个值给radio
    ASP.NET MVC实现权限控制
    为Guid数据类型的属性(property)赋值
    Razor语法中绑定一个值给checkbox
    判断IEnumerable<T>集合中是否包含有T对象
    SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
  • 原文地址:https://www.cnblogs.com/xl717/p/11636966.html
Copyright © 2011-2022 走看看