Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android解析JSON數據

android解析JSON數據

編輯:關於Android編程

JSONObject的使用

 一、 JSON對象的使用:

String content = "{'username': 'linux', 'password': '123456'}";
JSONObject jsonObject = new JSONObject(content);
String username = jsonObject.getString("username");
String password = jsonObject.getString("password");

二、 JSON數組的使用:

String jsonContent = "[{'user': '劉力', 'age': 21, 'femal': true}, "
            + "{'user': 'chen', 'age': 20, 'femal': false}]";
JSONArray jsonArray = new JSONArray(jsonContent);
for (int i = 0; i < jsonArray.length(); i++) {
   JSONObject object = jsonArray.getJSONObject(i);
   System.out.print(object.getString("user") + " ");
   System.out.print(object.getInt("age") + " ");
   System.out.print(object.getBoolean("femal") + " ");
   System.out.println();
}

三、 JSON數組與JSON對象混合使用

String jsonString = "[{'user': 'tomhu', 'age': 21, " + "'info': {'adress': 'hubai', 'sex': 'femal'}}, "
          + "{'user': 'chen', 'age': 20, " + "'info': {'adress': 'hunan', 'sex': 'male'}}]";
JSONArray jsonArrays = new JSONArray(jsonString);
for (int i = 0; i < jsonArrays.length(); i++) {
  JSONObject objects = jsonArrays.getJSONObject(i);
  System.out.print(objects.getString("user") + " ");
  System.out.print(objects.getInt("age") + " ");
  System.out.print(objects.getJSONObject("info").getString("adress") + " ");
  System.out.print(objects.getJSONObject("info").getString("sex") + " ");
  System.out.println();
}

四、 JSON數組中存儲對象

Person person = new Person();
person.setUsername("linux" );
person.setPassword("123456" );
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, person );
jsonArray.put(1, "I love you" );

// String username = jsonArray.getJSONObject(0).getString("username"); 錯誤的寫法
Person user = (Person) jsonArray.get(0);
System.out.println("username: " + user.getUsername());

JSONObject的原理

JsonObject的存儲與取出

一、 JSONObject裡面維護了一個LinkedHashMap,當生成一個無參數的JSONObject,實質是初始化了一個Map:

private final LinkedHashMap<String, Object> nameValuePairs;
public JSONObject() {
  nameValuePairs = new LinkedHashMap<String, Object>();
}

 二、 當JSONObject增加數據,實質上把數據的鍵值對方法存放在上述的Map中:

public JSONObject put(String name, boolean value) throws JSONException {
  nameValuePairs.put(checkName(name), value);
  return this;
}

三、 從JSONObject中取出數據,很容易想到的就是從Map取出了:

public String getString(String name) throws JSONException {
  Object object = get(name); // get()方法就是執行Object result = nameValuePairs.get(name);
  String result = JSON.toString(object);
  if (result == null) {
    throw JSON.typeMismatch(name, object, "String");
  }
  return result;
}

JsonObject的解析過程

一、 JsonObject還有一個帶參數的構造函數:常用的是傳遞一個String類型的參數

public JSONObject(String json) throws JSONException {
  this(new JSONTokener(json));
}

二、 跟進去,發現主要執行的是JSONTokener的nextValue()方法,在這個方法中主要是對數據進行解析;

public Object nextValue() throws JSONException {
  int c = nextCleanInternal();
  switch (c) {
    case -1:
      throw syntaxError("End of input");

    case '{':
      return readObject();

    case '[':
      return readArray();

    case '\'':
    case '"':
      return nextString((char) c);

    default:
      pos--;
      return readLiteral();
  }
}

在nextCleanInternal方法中,它會從頭到尾的逐個字符的解析,對於一些字符做一些處理。例如空格,換行,轉義符等!
當解析到[表示開始一個對象的讀取,當解析到{表示一個數組的讀取

三、 在readObject方法中,仍然是調用nextCleanInternal()方法,逐個得到解析的字符,下到解析到}.下面貼出重要代碼

int first = nextCleanInternal(); // 得到解析的字符
if (first == '}') {
  return result;
} else if (first != -1) {
  pos--;
}
.......
while (true) {
  Object name = nextValue(); // 解析得到鍵
  
  int separator = nextCleanInternal();
  if (separator != ':' && separator != '=') {
    throw syntaxError("Expected ':' after " + name);
  }
  if (pos < in.length() && in.charAt(pos) == '>') {
    pos++;
  }

  result.put((String) name, nextValue()); // 將解析得到的鍵值對,存放在map當中

  switch (nextCleanInternal()) {
    case '}':
      return result;
    case ';':
    case ',':
      continue;
    default:
      throw syntaxError("Unterminated object");
  }
}

四、 nextValue方法比較關鍵,它流轉解析的大部分工作!在nextValue中有一個readLiteral方法,針對一些類型做處理,得到解析之後的結果:

private Object readLiteral() throws JSONException {
  String literal = nextToInternal("{}[]/\\:,=;# \t\f");

  if (literal.length() == 0) {
    throw syntaxError("Expected literal value");
  } else if ("null".equalsIgnoreCase(literal)) {
    return JSONObject.NULL;
  } else if ("true".equalsIgnoreCase(literal)) {
    return Boolean.TRUE;
  } else if ("false".equalsIgnoreCase(literal)) {
    return Boolean.FALSE;
  }

  /* try to parse as an integral type... */
  if (literal.indexOf('.') == -1) {
    int base = 10;
    String number = literal;
    if (number.startsWith("0x") || number.startsWith("0X")) {
      number = number.substring(2);
      base = 16;
    } else if (number.startsWith("0") && number.length() > 1) {
      number = number.substring(1);
      base = 8;
    }
    try {
      long longValue = Long.parseLong(number, base);
      if (longValue <= Integer.MAX_VALUE && longValue >= Integer.MIN_VALUE) {
        return (int) longValue;
      } else {
        return longValue;
      }
    } catch (NumberFormatException e) {
      /*
       * This only happens for integral numbers greater than
       * Long.MAX_VALUE, numbers in exponential form (5e-10) and
       * unquoted strings. Fall through to try floating point.
       */
    }
  }

  /* ...next try to parse as a floating point... */
  try {
    return Double.valueOf(literal);
  } catch (NumberFormatException ignored) {
  }

  /* ... finally give up. We have an unquoted string */
  return new String(literal); // a new string avoids leaking memory
}

五、至於JSONArray的解析與JsonObject的解析過程是一樣的,它裡面維護的是一個List:

private final List<Object> values;
public JSONArray(JSONTokener readFrom) throws JSONException {
  Object object = readFrom.nextValue();
  if (object instanceof JSONArray) {
    values = ((JSONArray) object).values;
  } else {
    throw JSON.typeMismatch(object, "JSONArray");
  }
}

Gson的使用

一、我們在測試當中先加入一個Person類,方便測試:

package com.tomhu.test;

public class Person {
  private String name;
  private int age;

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
}

二、 gson把對象轉換成JSON格式

Gson gson = new Gson();
Person person = new Person();
person.setName("linux");
person.setAge(23);
String str = gson.toJson(person);
System.out.println(str);

打印結果:  {"name":"linux","age":23}

三、 gson把json格式解析成對象

String jsonData = "{'name':'劉力','age':19}";
Person person = gson.fromJson(jsonData, Person.class);
System.out.println(person.getName() + ", " + person.getAge());

打印結果: 劉力, 19

四、 gson把List對象解析成Json格式:

Gson gson = new Gson();
List<Person> persons = new ArrayList<Person>();
for (int i = 0; i < 2; i++) {
   Person p = new Person();
   p.setName("name" + i);
   p.setAge(i * 5);
   persons.add(p);
}
String str = gson.toJson(persons);
System.out.println(str);

打印結果: [{"name":"name0","age":0},{"name":"name1","age":5}]

五、 gson把Json格式解析成List對象:

Gson gson = new Gson();
String str = "[{'name':'linux','age':10},{'name':'huhx','age':22}]";
List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType());
for (int i = 0; i < ps.size(); i++) {
  Person person = ps.get(i);
  System.out.print("name: " + person.getName() + " age: " + person.getAge());
}

打印結果:name: linux age: 10 name: huhx age: 22

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved