Android JSON parsing Kotlin

Source: Internet
Author: User

I wrote it once. Kotlin parsing JSON But, it's really bad, it's just erased, and now it's all sorted out again. By the way, record a little problem that has been going on for a long time today.

1. Let's start with the simplest.

A JSON string: ===== is called jsonstring.

{ "code": "$", "MSG": "Success", "debugmsg": "", "result":{ "Data": "1231414"} }

Well, how to parse it???

You can use a function to

Fun         get_key_string (key:string,jsonstring:string): string {            = ""            try  {               val Jsonobj:jsonobject= jsonobject (jsonstring)                str=jsonobj.getstring (key)              Catch  (e:jsonexception) {                e.printstacktrace ()            }           return  str        } 

How to use it???

Val msg=get_key_string ("msg", "jsonstring")

The first parameter ===== in the JSON string, you want to parse the key, my example above is Code,msg,debugmsg,result, I chose msg

The second parameter, =====, is the name of the JSON string, which is a string, so don't think it's too complicated.

=====success results after MSG parsing

2. Multiple parsing

Is still the example above =====json string name is still called jsonstring

{ "code": "$", "MSG": "Success", "debugmsg": "", "result":{ "Data": "1231414"} }

I want to get data what to do???

Very simple, two-step.

Val result=get_key_string ("Result", "jsonstring")//===== here the second parameter is still jsonstring

Val data=get_key_string ("Data", "result")//===== note that the second parameter here has been turned into result.

3. Parsing int, Boolean type

This is like parsing a string type, just go to the code.

  

Fun Get_key_boolean (key:string,jsonstring:string): boolean {//Parse to boolean var str:boolean=true            Try{val Jsonobj:jsonobject=jsonobject (jsonstring) str=Jsonobj.getboolean (key)}Catch(e:jsonexception) {e.printstacktrace ()}returnstr} fun Get_key_int (key:string,jsonstring:string): int {//parse to int var str:int=0Try{val Jsonobj:jsonobject=jsonobject (jsonstring) str=Jsonobj.getint (key)}Catch(e:jsonexception) {e.printstacktrace ()}returnSTR}

4. A little bit of resolution ===== parse into list<map<string,any>>===== actually this is more general, a lot of things directly with this can be

For example, a more complicated jsonstring.

 

{  "code": "$",  "MSG": "Success",  "debugmsg": "",  "Result" : {              "data": [               "Key1": "string"
"Key2": 123
"Key3": True
                      ]
}
}

Such a jsonstring,key1 corresponds to a string, key2 corresponds to an integral type, Key3 corresponds to a Boolean type

How to parse it???

Fun Getlistmap (key:string, jsonstring:string): List<map<string, any>>{val list= Arraylist<map<string, any>>()            Try{val Jsonobject=Jsonobject (jsonstring) Val Jsonarray=Jsonobject.getjsonarray (Key) for(I in 0..jsonarray.length ()-1) {val JsonObject2=Jsonarray.getjsonobject (i) Val map= Hashmap<string, any>() Val iterator=Jsonobject2.keys () while(Iterator.hasnext ()) {Val Json_key=Iterator.next () var json_value:any? =jsonobject2.get (Json_key)if(Json_value = =NULL) {Json_value= ""} map.put (Json_key, Json_value)} List.add (map)}}Catch(e:jsonexception) {e.printstacktrace ()}returnList}

There are 2 main steps

Val result=get_key_string ("Result", "jsonstring")

Val Data=getlistmap ("Data", "result")

This is 666.

5. Wrap up all the methods you can use

classJsonutil {Companion object {fun get_key_string (key:string,jsonstring:string): string {var str: String= ""Try{val Jsonobj:jsonobject=jsonobject (jsonstring) str=jsonobj.getstring (key)}Catch(e:jsonexception) {e.printstacktrace ()}returnstr} fun Get_key_boolean (key:string,jsonstring:string): boolean {var str:boolean=true            Try{val Jsonobj:jsonobject=jsonobject (jsonstring) str=Jsonobj.getboolean (key)}Catch(e:jsonexception) {e.printstacktrace ()}returnstr} fun Get_key_int (key:string,jsonstring:string): int {var str:int=0Try{val Jsonobj:jsonobject=jsonobject (jsonstring) str=Jsonobj.getint (key)}Catch(e:jsonexception) {e.printstacktrace ()}returnstr} fun getList (key:string, jsonstring:string): List<String>{val list= arraylist<string>()            Try{val Jsonobject=Jsonobject (jsonstring) Val Jsonarray=Jsonobject.getjsonarray (Key) for(I in 0..jsonarray.length ()-1) {val msg=jsonarray.getstring (i) List.add (msg)}} Catch(e:jsonexception) {e.printstacktrace ()}returnlist} fun Getlistmap (key:string, jsonstring:string): List<map<string, any>>{val list= Arraylist<map<string, any>>()            Try{val Jsonobject=Jsonobject (jsonstring) Val Jsonarray=Jsonobject.getjsonarray (Key) for(I in 0..jsonarray.length ()-1) {val JsonObject2=Jsonarray.getjsonobject (i) Val map= Hashmap<string, any>() Val iterator=Jsonobject2.keys () while(Iterator.hasnext ()) {Val Json_key=Iterator.next () var json_value:any? =jsonobject2.get (Json_key)if(Json_value = =NULL) {Json_value= ""} map.put (Json_key, Json_value)} List.add (map)}}Catch(e:jsonexception) {e.printstacktrace ()}returnlist} fun Get_ask_item (key:string,jsonstring:string): ArrayList<myask>?{var myask=arraylist<myask>()            Try{val Jsonobject=Jsonobject (jsonstring) Val Jsonarray=Jsonobject.getjsonarray (Key) for(I in 0..jsonarray.length ()-1) {val Json_ask=Jsonarray.getjsonobject (i) var my_ask=Myask () Val commentcount=json_ask.getstring ("Commentcount") Val Commentid=json_ask.getstring ("Commentid") Val Content=json_ask.getstring ("Content") Val Createtime=json_ask.getstring ("Createtime") Val Gender=json_ask.getstring ("Gender") Val icon=json_ask.getstring ("icon") Val ID=json_ask.getstring ("id") Val Isfavorite=json_ask.getstring ("Isfavorite") Val Iszan=json_ask.getstring ("Iszan") Val Label=json_ask.getstring ("label") Val Link=json_ask.getstring ("link") Val Nickname=json_ask.getstring ("nickname") Val PublisherID=json_ask.getstring ("PublisherID") Val Reward=json_ask.getstring ("Reward") Val Type=json_ask.getstring ("type") Val Zan=json_ask.getstring ("Zan") Val Image_array=json_ask.getjsonarray ("image") var image_list:arraylist<string>?=NULL                     for(J1 in 0..image_array.length ()-1) {val Image_item=image_array.getstring (J1) image_list?. Add (Image_item)} Val thumbnailimage_array=json_ask.getjsonarray ("thumbnailimage") var image_list2:arraylist<string>?=NULL                     for(J2 in 0..thumbnailimage_array.length ()-1) {val Image_item=thumbnailimage_array.getstring (J2) Image_list2?. Add (Image_item)} My_ask.commentid=Commentid My_ask.commentcount=Commentcount my_ask.content=content My_ask.createtime=createtime My_ask.gender=Gender My_ask.icon=icon My_ask.id=ID My_ask.favoriteis=Isfavorite My_ask.zan=Zan My_ask.zanis=Iszan My_ask.label=label My_ask.link=Link My_ask.nickname=Nickname My_ask.publisherid=PublisherID My_ask.reward=Reward My_ask.type=type My_ask.image=image_list my_ask.thumbnailimage=Image_list2 Myask?. Add (my_ask)}returnMyask}Catch(e:jsonexception) {e.printstacktrace ()}returnmyask} }}
View Code

The last one is custom parsing, because the jsonstring in the project can be very complex, so define a class yourself and then parse it in a similar way.

Because my blog name is also called Jason_jan for JSON or a bit of a special, you can say that JSON is really good

  

Two third-party libraries recommended

Ason=====github Link: Https://github.com/afollestad/ason

Gsonformat=====github Link: Https://github.com/zzz40500/GsonFormat

Android JSON parsing Kotlin

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.