JsonObject解析 和JSonArray解析:

image.png

image.png
JSON創(chuàng)建和JSON解析:
一。
效果圖:

image.png
創(chuàng)建:

image.png
解析:

image.png
代碼----------------------
···
package com.example.json;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
//對象 和 數(shù)組
Button btCreat, btParse;
TextView tv;
String data="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
void init() {
tv = (TextView) findViewById(R.id.textView);
btCreat = (Button) findViewById(R.id.button);
btCreat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
createJson();
}
});
btParse = (Button) findViewById(R.id.button2);
btParse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
parseJson();
}
});
}
void createJson() {
//Json數(shù)據(jù)從形式上分成對象和數(shù)組兩種
//對象: JsonObject{key:value,key: value}
//數(shù)組: JsonArray[value ,value]
//1.創(chuàng)建根據(jù)需求的JsonObbject對象
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put("123456");
jsonArray.put("654321");
jsonObject.put("phone",jsonArray);
jsonObject.put("age",100);
jsonObject.put("name","zhangsan");
JSONObject jo=new JSONObject();
jo.put("country","China");
jo.put("province","jiangsu");
jsonObject.put("address",jo);
jsonObject.put("married",false);
data=jsonObject.toString();
tv.setText("創(chuàng)建的Json數(shù)據(jù)為:\n"+data);
} catch (Exception e) {
e.printStackTrace();
}
}
public void parseJson(){
String content = "";
try {
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("phone");
content += "手機(jī)號:";
for (int i = 0; i < jsonArray.length(); i++) {
content += jsonArray.getString(i)+" ";
}
content += "\n"+"姓名:"+jsonObject.getString("name");
content += "\n"+"年齡:"+jsonObject.getInt("age");
JSONObject jo = jsonObject.getJSONObject("address");
content += "\n"+"國家:"+jo.getString("country");
content += "\n"+"省份:"+jo.getString("province");
content += "\n"+jsonObject.getBoolean("married");
tv.setText("解析的結(jié)果是:\n"+content);
} catch (Exception e) {
e.printStackTrace();
}
}
}
···