您的位置:首页 > Web前端 > JavaScript

创建并读取JSON格式数据

2016-01-12 21:05 627 查看
创建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) {
// TODO Auto-generated catch block
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 是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符
InputStreamReader isr = new InputStreamReader(getAssets().open("test.json"),"UTF-8");
BufferedReader br = new BufferedReader(isr);

String line;
StringBuilder builder = new StringBuilder();

//br.readLine()表示读取一个文本行
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) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: