标签:pac bean 内容 sonar pre aaa put import hand
1. 首先讲一下什么是Json--下面的就是Json基本格式,其实就是一个键值对。
{ "people": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
]}
2.
package Util
import com.example.jason_jan.guangdamiao.bean.Person
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.ArrayList
import java.util.HashMap
/**
* Created by Jason_Jan on 2017/7/5.
*/
class JsonUtil {
companion object {
/**
* 获取对象数据
* @param key
* *
* @param jsonString
* *
* @return
*/
fun getPerson(key: String, jsonString: String): Person {
val person = Person()
try {
val jsonObject = JSONObject(jsonString)
val personObject = jsonObject.getJSONObject(key)
person.UserID = personObject.getString("UserID")//这里看情况修改
} catch (e: JSONException) {
e.printStackTrace()
}
return person
}
/**
* 获取对象数组数据
* @param key
* *
* @param jsonString
* *
* @return
*/
fun getPersons(key: String, jsonString: String): List<Person> {
val list = ArrayList<Person>()
try {
val jsonObject = JSONObject(jsonString)
//返回json的数组
val jsonArray = jsonObject.getJSONArray(key)
for (i in 0..jsonArray.length() - 1) {
val jsonObject2 = jsonArray.getJSONObject(i)
val person = Person()//这里看情况修改
list.add(person)
}
} catch (e: JSONException) {
e.printStackTrace()
}
return list
}
/**
* 获取String数组数据
* @param key
* *
* @param jsonString
* *
* @return
*/
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()
}
return list
}
/**
* 获取对象的Map集合数据
* @param key
* *
* @param jsonString
* *
* @return
*/
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()
}
return list
}
}
}
2.使用方法,非常简单。在handler中调用
如var person:Person--这里声明一个Person类
person=JsonUtil.getPerson("Json返回的关键字",HttpUtil中得到的内容)
txt1.text=person.toString()--txt1是布局中的一个textView
3.其实Json解析一般都要和Http挂钩,仔细琢磨,你会收获很多。
标签:pac bean 内容 sonar pre aaa put import hand
原文地址:http://www.cnblogs.com/Jason-Jan/p/7127143.html