zoukankan      html  css  js  c++  java
  • Scala【json字符串和json对象互相转换】

    pom依赖

            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.62</version>
            </dependency>
    

    1.读取文件

    val product:List[String] = Source.fromFile("F:\Scala\product.txt","utf-8").getLines().toList
    

    2.Json字符串JSON对象互转

    import com.alibaba.fastjson.JSON
    import java.util
    import com.alibaba.fastjson.serializer.SerializeFilter
    import scala.beans.BeanProperty
    
    /**
     * @description: Json字符串和JSON对象互转
     * @author: HaoWu
     * @create: 2020年07月28日
     */
    object JsonTranslate {
      def main(args: Array[String]): Unit = {
    
        val jsonStr = "{"schoolName":"A",clazzs:[{"className":"1001"},{"className":"1002"},{"className":"1003"}]}"
    
        //json字符串转JSON对象
        val school = JSON.parseObject(jsonStr,classOf[School])
        println(school.schoolName)
        //隐式转换将Java的List转为Scala的List
        import scala.collection.JavaConversions._
        school.clazzs.foreach(x=>println(x.className))
    
        //JSON对象转json字符串
        println("*"*10)
        println(JSON.toJSONString(school, null.asInstanceOf[Array[SerializeFilter]]))
      }
    }
    //使用fastJson将对象转json字符串的时候必须加上@BeanProperty
    //转JSON对象需要用java里面的List,导入java.util包
    case class School(@BeanProperty schoolName:String,@BeanProperty clazzs:util.List[Clazz])
    case class Clazz(@BeanProperty className:String)
    

    注意

    1.从json文件读取的的字符串是如果有List,需要用java的list接收,导入java.util

    2.如果需要将java的List转换成scala的List的需要导入scala.collection.JavaConversions._包,进行隐式转换自动将java List转为scala List。

    3.JSON对象转json的字符串需要JSON对象对应得实体类有get,set方法。通过@BeanProperty注解实现。

  • 相关阅读:
    win10前面板耳机没声音
    学计算机的值得一看的文章,跟帖也很有水平啊
    ubuntu下编译caffe
    pip卡住不动的解决方案
    数字图像处理处理中的数学怎么提高?
    安装vmall5:从ebak恢复数据,需要配置php.ini
    python入门(7)Python程序的风格
    python入门(6)输入和输出
    python入门(5)使用文件编辑器编写代码并保存执行
    python入门(4)第一个python程序
  • 原文地址:https://www.cnblogs.com/wh984763176/p/13391154.html
Copyright © 2011-2022 走看看