package com.example.day15_jsondemo;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
/**
*
* json的解析
*
* @author Administrator
*
*/
public class MainActivity extends Activity {
private TextView content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = (TextView) findViewById(R.id.content);
}
public void object(View view) {
/**
* 1.newJSONOBJect();—-字符串 2.获取
*/
try {
InputStream inputStream = getAssets().open(“json1.json”);
// 输入流—>String
String string = stream2String(inputStream);
// 解析字符串
JSONObject jsonObject = new JSONObject(string);
// 取值{“name”:”小明”,”age”:12}
String name = jsonObject.getString(“name”);
int age = jsonObject.getInt(“age”);
System.out.println(“name–” + name + “age–” + age);
// Toast.makeText(MainActivity.this, text, duration).show();
content.setText(“name–” + name + “age–” + age);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 解析數組
public void array(View view) {
content.setText(“”);
try {
InputStream inputStream = getAssets().open(“json2.json”);
// 输入流—>String
String string = stream2String(inputStream);
// 解析字符串
JSONArray jsonArray = new JSONArray(string);
// 遍歷
for (int i = 0; i < jsonArray.length(); i++) {
// 取值
JSONObject jsonObject = jsonArray.getJSONObject(i);
// 根據鍵取值
String name = jsonObject.getString(“name”);
int age = jsonObject.getInt(“age”);
// 顯示
content.append(“name–” + name + “age–” + age + “\n”);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 混合型,數組和對象
public void mix(View view) {
content.setText(“”);
// 讀取流,–String
try {
InputStream inputStream = getAssets().open(“json3.json”);
String string = stream2String(inputStream);
// jsonarray 數組
JSONArray jsonArray = new JSONArray(string);
// 遍历
for (int i = 0; i < jsonArray.length(); i++) {
// 获取每个对象
JSONObject jsonObject = jsonArray.getJSONObject(i);
// 获取 user,age
String name = jsonObject.getString(“user”);
int age = jsonObject.getInt(“age”);
// info对象
JSONObject jsonObject2 = jsonObject.getJSONObject(“info”);
// 获取info里的数据
String address = jsonObject2.getString(“adress”);
String sex = jsonObject2.getString(“sex”);
// 展示
content.append(“name-” + name + “–age–” + age + “–address–”
+ address + “–sex–” + sex + “\n”);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// //输入流—>String
public String stream2String(InputStream inputStream) throws IOException {
// 字节数据输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
// 写入输出流
baos.write(buffer, 0, len);
}
return baos.toString();
}
}