今天学习了一下解析json的知识,把我学习的的一个小例子拿出来和大家分享一下
下面是代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String x;
JSONObject obj;
try {
InputStream is = this.getResources().openRawResource(R.raw.json);
byte [] buffer = new byte[is.available()] ;
is.read(buffer);
TextView v = new TextView(this);
String json = new String(buffer,"utf-8");
obj = new JSONObject(json);
x = obj.getString("名称");
Log.d("======名称========",x);
x = obj.getString("网址");
Log.d("======网址========",x);
x = obj.getString("摘要");
Log.d("======摘要========",x);
JSONObject obj1 = obj.getJSONObject("网址数据");
x = obj1.getString("综合");
Log.d("======综合========",x);
x = obj1.getString("级别");
Log.d("======级别========",x);
x = obj1.getString("数量");
Log.d("======数量========",x);
JSONArray array = obj1.getJSONArray("综合");
obj = array.getJSONObject(0);
x = obj.getString("综合1");
Log.d("======综合1========",x);
obj = array.getJSONObject(1);
x = obj.getString("综合2");
Log.d("======综合2========",x);
JSONStringer s = new JSONStringer();
Log.d("======================",s.object().key("a").value("aaa").endObject().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json文件:
{
"名称":"ssss",
"网址":" 网址",
"摘要":"",
"网址数据":
{
"数量":"60",
"级别":"61",
"单位":"62",
"综合":
[
{
"综合1":"100"
},
{
"综合2":"110"
}
]
}
}
下面是代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String x;
JSONObject obj;
try {
InputStream is = this.getResources().openRawResource(R.raw.json);
byte [] buffer = new byte[is.available()] ;
is.read(buffer);
TextView v = new TextView(this);
String json = new String(buffer,"utf-8");
obj = new JSONObject(json);
x = obj.getString("名称");
Log.d("======名称========",x);
x = obj.getString("网址");
Log.d("======网址========",x);
x = obj.getString("摘要");
Log.d("======摘要========",x);
JSONObject obj1 = obj.getJSONObject("网址数据");
x = obj1.getString("综合");
Log.d("======综合========",x);
x = obj1.getString("级别");
Log.d("======级别========",x);
x = obj1.getString("数量");
Log.d("======数量========",x);
JSONArray array = obj1.getJSONArray("综合");
obj = array.getJSONObject(0);
x = obj.getString("综合1");
Log.d("======综合1========",x);
obj = array.getJSONObject(1);
x = obj.getString("综合2");
Log.d("======综合2========",x);
JSONStringer s = new JSONStringer();
Log.d("======================",s.object().key("a").value("aaa").endObject().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json文件:
{
"名称":"ssss",
"网址":" 网址",
"摘要":"",
"网址数据":
{
"数量":"60",
"级别":"61",
"单位":"62",
"综合":
[
{
"综合1":"100"
},
{
"综合2":"110"
}
]
}
}