json是一种轻量级的数据交换格式,易于阅读和编写,也易于机器解析和生成。在json中格式要求为数组或对象,只能有字符串,数字或布尔型值,属性名也需要加引号。json字符串也是在平时开发中使用较多的。本文将向大家演示json解析字符串代码。
json字符串应满足以下条件:
1:它必须是一个字符串,由" "或者' '包裹数据,支持字符串的各种操作
2:里面的数据格式应该要满足其中一个格式,可以是json对象,也可以是json对象数组或者是两种基本形式的组合变形。
解析JSON字符串代码分为三种情况,一个JavaBean,一个List数组,一个嵌套Map的List数组:
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import com.android.myjson.domain.Person; public class JsonTools { public static Person getPerson(String key, String jsonString) { Person person = new Person(); try { JSonObject jsonObject = new JSonObject(jsonString); JSonObject personObject = jsonObject.getJSonObject("person"); person.setId(personObject.getInt("id")); person.setName(personObject.getString("name")); person.setAddress(personObject.getString("address")); } catch (Exception e) { // TODO: handle exception } return person; } public static List getPersons(String key, String jsonString) { List list = new ArrayList(); try { JSonObject jsonObject = new JSonObject(jsonString); // 返回json的数组 JSonArray jsonArray = jsonObject.getJSonArray(key); for (int i = 0; i < jsonArray.length(); i++) { JSonObject jsonObject2 = jsonArray.getJSonObject(i); Person person = new Person(); person.setId(jsonObject2.getInt("id")); person.setName(jsonObject2.getString("name")); person.setAddress(jsonObject2.getString("address")); list.add(person); } } catch (Exception e) { // TODO: handle exception } return list; } public static List getList(String key, String jsonString) { List list = new ArrayList(); try { JSonObject jsonObject = new JSonObject(jsonString); JSonArray jsonArray = jsonObject.getJSonArray(key); for (int i = 0; i < jsonArray.length(); i++) { String msg = jsonArray.getString(i); list.add(msg); } } catch (Exception e) { // TODO: handle exception } return list; } public static List> listKeyMaps(String key, String jsonString) { List> list = new ArrayList>(); try { JSonObject jsonObject = new JSonObject(jsonString); JSonArray jsonArray = jsonObject.getJSonArray(key); for (int i = 0; i < jsonArray.length(); i++) { JSonObject jsonObject2 = jsonArray.getJSonObject(i); Map map = new HashMap(); Iterator iterator = jsonObject2.keys(); while (iterator.hasNext()) { String json_key = iterator.next(); Object json_value = jsonObject2.get(json_key); if (json_value == null) { json_value = ""; } map.put(json_key, json_value); } list.add(map); } } catch (Exception e) { // TODO: handle exception } return list; } }
以上就是json解析字符串代码演示,希望能对你有所帮助哦~