依赖
< dependency>
< groupId> com. alibaba< / groupId>
< artifactId> fastjson< / artifactId>
< version> 1.2 .47 < / version>
< / dependency>
构建json对象
def test1( ) : Unit = {
val nObject = new JSONObject( )
nObject. put( "name" , "xiaoming" )
nObject. put( "age" , 23 )
println( nObject)
}
json字符串转json对象
def decode( ) : Unit = {
val str = "{'name':'xiaoming','age':23}"
val nObject: JSONObject = JSON. parseObject( str)
val str1: String = nObject. getString( "name" )
println( s"str1 = ${str1}" )
}
Json对象转字符串
def json2str( ) : Unit = {
val str = "{'name':'xiaoming','age':23}"
val nObject: JSONObject = JSON. parseObject( str)
val string: String = nObject. toJSONString
println( s"string = ${string}" )
}
提取json字符串中数组的部分信息
def getarray( ) : Unit = {
import com. alibaba. fastjson. JSONArray
import com. alibaba. fastjson. JSONObject
val str: String = "{\n" + "'name':'网站',\n" + "'num':3,\n" + "'sites':[ 'Google', 'Runoob', 'Taobao' ]\n" + "}"
val jsonObject: JSONObject = JSON. parseObject( str)
val sites: String = jsonObject. getString( "sites" )
val array: JSONArray = JSON. parseArray( sites)
System. out. println( array. get( 0 ) )
}
参考
Java 中 JSON 的使用 | 菜鸟教程