文章目录
  1. 1. 简单介绍
  2. 2. 使用实例

简单介绍

在Android中默认提供了org.json的jar包用于处理JSON数据。另外也可以自己导入上篇介绍的在Java中生成和解析JSON数据的jar包,谷歌也提供了Gson用于处理JSON格式的的数据。都尝试过,个人觉得在Android中还是使用org.json来处理JSON数据方便简洁。

使用实例

主类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.carlos.json;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {

private TextView textView;
private JSONObject object;
private JSONArray array;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textView = (TextView) findViewById(R.id.textview);

// 生成JSON数据
try {
array = new JSONArray();
object = new JSONObject();
object.put("username", "Carlos");
object.put("password", "123456");
array.put(object);
object = new JSONObject();
object.put("username", "Jack");
object.put("password", "654321");
array.put(object);
object = new JSONObject();
object.put("users", array);
System.out.println(object.toString());
textView.setText("生成的JSON数据为:\n" + object.toString() + "\n");
Log.i("JSON", "生成的JSON数据为:\n" + object.toString());
} catch (JSONException e) {
Log.e("JSON", "生成JSON数据异常");
e.printStackTrace();
}

// 解析JSON数据
try {
object = new JSONObject(object.toString());
array = object.getJSONArray("users");
textView.append("\n解析得到的结果为:\n");
Log.i("JSON", "解析JSON数据得到的结果");
for (int i = 0; i < array.length(); i++) {
object = array.getJSONObject(i);
String username = object.getString("username");
String password = object.getString("password");
textView.append("用户名:" + username + "的密码为:" + password + "\n");
Log.i("JSON", "用户名:" + username + "的密码为:" + password);
}
} catch (JSONException e) {
Log.e("JSON", "解析JSON数据异常");
e.printStackTrace();
}

}
}

xml布局

1
2
3
4
5
6
7
8
9
10
11
12
13
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >

<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

</RelativeLayout>

Genymotion里面显示的结果

Logcat日志中显示的结果

文章目录
  1. 1. 简单介绍
  2. 2. 使用实例