[Android] Use JSONObiect and Gson related methods to realize mutual conversion between json data and kotlin objects

Table of contents

1. What is JSON?

2. JSON data format

3. Related APIs

1.JSONObject:

   2.Gson

  4. Use JSONObject

Convert json-formatted string {} to kotlin object

Convert String[] in json format to List of kotlin objects

5. Use GSON

To add dependencies first

Convert json-formatted string {} to kotlin object 

 Convert String[] in json format to List of kotlin objects

convert kotlin object to json string{}

Convert List of kotlin objects to json string[]

6. Use Map to encapsulate the special case of json object key


1. What is JSON?

  • JSON (JavaScript Object Notation) is a lightweight data exchange format
  • The essence is a string with a specific format
  • JSON data is already the most common choice for client-server interaction, and xml is rarely used for data interaction

Advantages and disadvantages of JSON over XML:

Advantages: JSON is smaller in size and saves traffic when transmitted on the network.

Disadvantages: Poor semantics, looks less intuitive than XML. 

How to get data in JSON format

For friends who are just starting to learn JSON, there will always be a problem: how to get data in JSON format, if you have the same problem now, you can try my other blog http://t.csdn.cn/JNaXQ There are detailed introductions.

2. JSON data format

  • the whole frame

           Json array: []

           Json object: {}

  • The structure of the Json array: [value1,value2,value3]
  • The structure of the Json object: {key1: value1, key2: value2, key3: value3}
  • data type of key: string
  • The data type of value

            value string null json array json object

  • example

        [1,"abcd",[{"a",1}],{"b":2,"c":[]}]

3. Related APIs

1.JSONObject:

  • JsonObject: json object {}

           JSONObject( json:String): parse the json string into a json object

           Xxx.getXxx(name:String): Get the corresponding Value in the json object according to the name

  • JsonArray: json array []

       JSONArray(json:String ): parses a json string into a json array

        length(): Get the number of elements in the json array

        Xxx.getJSONObject(index:int ): Obtain the corresponding element data in the json array according to the subscript

   2.Gson

  • Gson: a class that can parse json data

       Gson(): Method for constructing objects

       toJson(src:Object): Convert the object to a json string in the corresponding format

       fromJson(json:String,typeOfT:Type):T: parse the JSon string to get the object

  • TypeToken<T>: the class used to get Type

       protected TypeToken(): protected construction method

       getType():Type: get the type object

  4. Use JSONObject

Convert json -formatted string {} to kotlin object

1. Encapsulate the json string into a JSONObject object

2. Obtain the corresponding value from the object according to the key

private fun JsonToObject(jsonData:String){
        try {
            //1.将json字符串封装成JSONObject对象
            val jsonObject:JSONObject= JSONObject(jsonData)
            //2.从对象中根据key得到对应的value
            val id:Int=jsonObject.getInt("id")
            val name:String=jsonObject.getString("name")
            val price:Double=jsonObject.getDouble("price")
            val imagePath:String=jsonObject.getString("imagePath")
            Log.d("data","id is $id")
            Log.d("data","name is $name")
            Log.d("data","price is $price")
            Log.d("data","imagePath is $imagePath")
        }catch (e:Exception){
            e.printStackTrace()
        }
}

Convert String[] in json format to List of kotlin objects

1. Wrap the json string into the JSONArray object

2. Traverse all elements of the JSONArray object (JSONObject), encapsulate each element as shopInfo, and add it to the List

private fun JsonToList(jsonData:String){
        try {
            val list= ArrayList<ShopInfo>()
            //1.将json字符串包装JSONArray对象
            val jsonArray= JSONArray(jsonData)
            //2.遍历JSONArray对象所以元素(JSONObject),并将每个元素封装为shopInfo,
             //并添加到List
            for(i in 0 until jsonArray.length()){
                val jsonObject=jsonArray.getJSONObject(i)
                //从对象中根据key得到对应value
                val id:Int=jsonObject.getInt("id")
                val name:String=jsonObject.getString("name")
                val price:Double=jsonObject.getDouble("price")
                val imagePath:String=jsonObject.getString("imagePath")
                Log.d("data","id is $id")
                Log.d("data","name is $name")
                Log.d("data","price is $price")
                Log.d("data","imagePath is $imagePath")
                list.add(ShopInfo(id,name,price,imagePath))
            }
        }catch (e:Exception) {
            e.printStackTrace()
        }
}

5. Use GSON

To add dependencies first

implementation 'com.google.code.gson:gson:2.8.5'

Convert json -formatted string {} to kotlin object 

 private fun JsonToObjectGson(jsonData:String){
        val gson=Gson()
        val shopInfo=gson.fromJson(jsonData,ShopInfo::class.java)
 }

 Convert String[] in json format to List of kotlin objects

 private fun JsonToListGson(jsonData:String){
        val gson=Gson()
        val typeOf=object:TypeToken<List<ShopInfo>>(){}.type
        val list=gson.fromJson<List<ShopInfo>>(jsonData,typeOf)
        for (a in list){
            Log.d("data","id is $a.id")
            Log.d("data","name is $a.name")
            Log.d("data","price is $a.price")
            Log.d("data","imagePath is $a.imagePath")
        }
    }

convert kotlin object to json string{}

 private fun ObjectToJson(){
        val info:ShopInfo= ShopInfo(4,"小名",11.0,"http://www.ddd.com")
        val json:String=Gson().toJson(info)
        Log.d("data",json)
    }

Convert List of kotlin objects to json string[]

private fun ListToJson(){
        val list=ArrayList<ShopInfo>()
        list.add(ShopInfo(4,"小名",11.0,"http://www.ddd.com"))
        list.add(ShopInfo(5,"小星",21.0,"http://www.eee.com"))
        val json:String=Gson().toJson(list)
        Log.d("data",json)
 }

6. Use Map to encapsulate the special case of json object key

When the key of the json object does not conform to the variable naming rules, such as: my name (with spaces in the variable) or 2, this member variable cannot be added to the ShopInfo class, how to solve it?

We can convert json object to Map .

 private fun JsonToMap(jsonString:String) {
        val json=Gson()
        val typeOf=object :TypeToken<Map<String,Objects>>(){}.type
       val map:Map<String,Objects> = json.fromJson(jsonString,typeOf)
        Log.d("data",map.toString())
 }

Guess you like

Origin blog.csdn.net/weixin_63357306/article/details/128441246