在Android网络交互中使用到JSON传输接收数据。
JSONObject为键值对形式的数据,内部使用LinkedHashMap实现。键的类型固定为String,值可取的类型在JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL.NULL是JSONObject中自定义的一个Object,代表键没有对应的值。其中覆盖了Object中的equals和toString方法:public static final Object NULL = new Object() { @Override public boolean equals(Object o) { return o == this || o == null; // API specifies this broken equals implementation } @Override public String toString() { return "null"; } };值不能取为 null,Double#isNaN(),Double#isInfinite()或其他任何没有列在这儿的值。常用的方法:构造JSONObject: public JSONObject();public JSONObject(Map copyFrom);public JSONObject(JSONTokener readFrom) throws JSONException;这个构造函数用来从符合JSON格式的String中构造JSONTokener,然后构造JSONObject。public JSONObject(String json) throws JSONException { this(new JSONTokener(json)); }向JSONObject中写入数据:
put(String name, T value), T为Java基本类型boolean, double, int, long。在数据写入的过程中T会被包裹。put(String name, Object value), 若value为null,name对应的键值对会从JSONObject中移除。从JSONObject中读取数据:
public Object get(String name) throws JSONException;public double getDouble(String name) throws JSONException;public boolean getBoolean(String name) throws JSONException;public int getInt(String name) throws JSONException;public long getLong(String name) throws JSONException;public String getString(String name) throws JSONException;public JSONArray getJSONArray(String name) throws JSONException;public JSONObject getJSONObject(String name) throws JSONException;这些get方法在找不多值或值类型不匹配的时候都会抛出异常,注意异常处理。
get方法有一个无异常的版本。以Long举例:public long optLong(String name); 在找不到值时返回OLpublic long optLong(String name, long fallback):在找不到值时返回fallbackJSON使用的常见场景是构造JSONObject后转化会String发往服务器,或从服务器接收到String后转化为JSONObject。
JSONObject to String:public String toString(); 将JSONObject对象转为String 比如这种格式:{"query":"Pizza","locations":[94043,90210]}public String toString(int indentSpaces) throws JSONException;将JSON对象转换为带换行缩进的便于调试,阅读的String比如下面的格式:{ "query": "Pizza", "locations": [ 94043, 90210 ] }String to JSONObject
使用JSONObject的构造函数:public JSONObject(String json) throws JSONException;