android json怎么打开,如何在Android中Json解析

可能是这段代码帮助你

public class JSONfunctions {

public static JSONArray getJSONfromURL(String url) {

InputStream is = null;

String result = "";

JSONArray jArray = null;

// http post

try {

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost(url);

HttpResponse response = httpclient.execute(httppost);

HttpEntity entity = response.getEntity();

is = entity.getContent();

} catch (Exception e) {

Log.e("log_tag", "Error in http connection " + e.toString());

}

// convert response to string

try {

BufferedReader reader = new BufferedReader(new InputStreamReader(

is, "iso-8859-1"), 8);

StringBuilder sb = new StringBuilder();

String line = null;

while ((line = reader.readLine()) != null) {

sb.append(line + "

");

}

is.close();

result = sb.toString();

} catch (Exception e) {

Log.e("log_tag get data string ",

"Error converting result " + e.toString());

}

try {

jArray = new JSONArray(result);

} catch (JSONException e) {

Log.e("log_tag create object ",

"Error parsing data " + e.toString());

}

return jArray;

}

}

这是解析代码示例,您可以更改它.

public class Main extends ListActivity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.listplaceholder);

JSONArray json = JSONfunctions

.getJSONfromURL("http://docs.blackberry.com/sampledata.json");

for (int i = 0; i < json.length(); i++) {

try {

Log.e("json names vehicleType", ""

+ json.getJSONObject(i).getString("vehicleType"));

Log.e("json names vehicleColor", ""

+ json.getJSONObject(i).getString("vehicleColor"));

Log.e("json names fuel",

"" + json.getJSONObject(i).getString("fuel"));

Log.e("json names treadType", ""

+ json.getJSONObject(i).getString("treadType"));

Log.e("json names approvedOperators",

""

+ json.getJSONObject(i).getJSONArray(

"approvedOperators"));

JSONArray array = json.getJSONObject(i).getJSONArray(

"approvedOperators");

for (int j = 0; j < array.length(); j++) {

Log.e("json names approvedOperators name ", ""

+ array.getJSONObject(j).getString("name"));

Log.e("json names approvedOperators experience ",

""

+ array.getJSONObject(j).getString(

"experiencePoints"));

}

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值