Android JSON
- package sn.len.json;
-
-
import org.json.JSONArray;
-
import org.json.JSONException;
-
import org.json.JSONObject;
-
-
import android.app.Activity;
-
import android.os.Bundle;
-
import android.util.Log;
-
-
public class JSONActivity extends Activity {
-
private String jsondata;
-
@Override
-
public void onCreate(Bundle savedInstanceState)
- {
-
super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
try
- {
-
//调用构建JSON字符串方法
- buildJson();
- }
-
catch (JSONException e)
- {
- e.printStackTrace();
- }
- }
-
//构建JSON字符串
-
public void buildJson() throws JSONException
- {
-
JSONArray json=new JSONArray();
-
JSONObject jsonObj=new JSONObject();
-
for(int i=0;i<2;i++)
- {
-
jsonObj.put("id", "001");
-
jsonObj.put("age", "20");
-
jsonObj.put("name", "snoanw");
-
//把每个数据当作一对象添加到数组里
- json.put(jsonObj);
- }
- jsondata=json.toString();
-
Log.i("JSON", jsondata);
-
//调用解析JSON方法
- parserJson(jsondata);
- }
-
// 解析JSON字符串
-
public void parserJson(String jsondata) throws JSONException
- {
-
//构建JSON数组对象
-
JSONArray json1=new JSONArray(jsondata);
-
for(int i=0;i<json1.length();i++)
- {
- JSONObject jsonObj2=json1.optJSONObject(i);
-
String id=jsonObj2.getString("id");
-
String age=jsonObj2.getString("age");
-
String name=jsonObj2.getString("name");
-
Log.i("JSONDATA", id+age+name);
- }
- }
- }
相关文章:
-
2022-12-23
-
2022-12-23
-
2021-09-10
-
2021-09-10
-
2021-12-17
-
2021-07-08
-
2021-07-21
猜你喜欢
-
2021-07-17
-
2021-09-10
-
2021-09-10
-
2021-11-20
-
2022-12-23
相关资源
-
下载
2022-12-09
-
下载
2021-06-23
-
下载
2021-07-01