当前位置:网站首页>[groovy] JSON string deserialization (use jsonslurper to deserialize JSON strings | construct related classes according to the map set)

[groovy] JSON string deserialization (use jsonslurper to deserialize JSON strings | construct related classes according to the map set)

2022-07-06 00:34:00 Programmer community

List of articles

  • One 、 Use JsonSlurper Conduct json String deserialization
  • Two 、 according to map Collection construction related classes
  • 3、 ... and 、 Complete code example

One 、 Use JsonSlurper Conduct json String deserialization


Will be as follows json character string

{ 
    "age":18,"name":"Tom"}

deserialize ;

First , establish JsonSlurper object ,

def jsonSlurper = new JsonSlurper()

then , Call the JsonSlurper Object's parse Method , Different types of json Data is deserialized ;

Deserializable json The data type is shown in the figure below :

 Insert picture description here

This call jsonSlurper Object's parseText Method , take json Deserialize the string ;

//  String  json  Deserialization operation  ,  obtain  map  aggregate def jsonObject = jsonSlurper.parseText('{"age":18,"name":"Tom"}');

Print the deserialization result ,

//  Print the deserialization result println jsonObject

The results are as follows :

[age:18, name:Tom]

Two 、 according to map Collection construction related classes


In the above chapter json character string

{ 
    "age":18,"name":"Tom"}

deserialize , obtain

[age:18, name:Tom]

map aggregate ;

The map The set can be directly assigned to the corresponding class object , The variable name of this class is map A collection of Key key ;

//  according to  map  A collection of  Key  Construction class class Student { 
        def name    def age}

Direct will map Set is assigned to the constructed class object , And print the member variable value of the object ;

//  Direct will  map  Set is assigned to the constructed class object Student student = jsonObject//  Print the value of the member variable of the class object println "${student.name} , ${student.age}"

The execution result is :

Tom , 18

3、 ... and 、 Complete code example


Complete code example :

import groovy.json.JsonSlurper//  take  {"age":18,"name":"Tom"}  String is deserialized def jsonSlurper = new JsonSlurper()//  String  json  Deserialization operation  ,  obtain  map  aggregate def jsonObject = jsonSlurper.parseText('{"age":18,"name":"Tom"}');//  Print the deserialization result println jsonObject//  according to  map  A collection of  Key  Construction class class Student { 
        def name    def age}//  Direct will  map  Set is assigned to the constructed class object Student student = jsonObject//  Print the value of the member variable of the class object println "${student.name} , ${student.age}"

Execution results :

[age:18, name:Tom]Tom , 18

 Insert picture description here

原网站

版权声明
本文为[Programmer community]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140223050562.html