- 创建JSON格式的数据
package com.example.testjson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
JSONObject lan1 = new JSONObject();
JSONObject lan2 = new JSONObject();
JSONObject lan3 = new JSONObject();
lan1.put("firstName", "John");
lan1.put("lastName", "Doe");
lan2.put("firstName", "Anna");
lan2.put("lastName", "Smith");
lan3.put("firstName", "Peter");
lan3.put("lastName", "Jones");
JSONArray array = new JSONArray();
array.put(lan1);
array.put(lan2);
array.put(lan3);
JSONObject root = new JSONObject();
root.put("employees", array);
System.out.println(root.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
- 读取JSON格式数据:
JSON文件:test.json,并把它放在eclipse android的assets目录下
{
“employees”:
[
{ “firstName”:”John” , “lastName”:”Doe” },
{ “firstName”:”Anna” , “lastName”:”Smith” },
{ “firstName”:”Peter” , “lastName”:”Jones” }
]
}
package com.example.testjson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
InputStreamReader isr = new InputStreamReader(getAssets().open("test.json"),"UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder builder = new StringBuilder();
while((line = br.readLine()) != null){
builder.append(line);
}
br.close();
isr.close();
JSONObject root = new JSONObject(builder.toString());
JSONArray array = root.getJSONArray("employees");
for(int i = 0;i < array.length();i++){
JSONObject lan = array.getJSONObject(i);
System.out.println(i);
System.out.println(lan.getString("firstName") + "----" + lan.getString("lastName"));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}