JsonObject解析 和JSonArray解析:
image.png
image.png
JSON创建和JSON解析:
一。
效果图:
image.png
创建:
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 {
//对象 和 数组
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数据从形式上分成对象和数组两种
//对象: JsonObject{key:value,key: value}
//数组: JsonArray[value ,value]
//1.创建根据需求的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("创建的Json数据为:\n"+data);
} catch (Exception e) {
e.printStackTrace();
}
}
public void parseJson(){
String content = "";
try {
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("phone");
content += "手机号:";
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("解析的结果是:\n"+content);
} catch (Exception e) {
e.printStackTrace();
}
}
}
···
网友评论