大家好,又见面了,我是你们的朋友全栈君。
我目前正在学习一些使用JAVA的
android编程.我的老师分享了这段代码,它将使用API,获取其
JSON文件,并将其转换为
JSONArray文件.然后,他将遍历该JSONArray并将它们放入ArrayList,然后将它们显示在一个活动上.
问题是我正在使用的API会返回一个JSONObject文件,而我不知道如何正确地将其转换为JSONArray.
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = “UTF-8”;
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONArray jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONArray makeHttpRequest(String url, String method) {
sbParams = new StringBuilder();
if(method.equals(“GET”)){
// request method is GET
if (sbParams.length() != 0) {
url += “?” + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod(“GET”);
conn.setRequestProperty(“AccountKey”, “pVU56+0hI26DNLeTzlU/Dw==”);
conn.setRequestProperty(“UniqueUserId”, “33c07f2f-b4c0-4151-acd3-e0829b303d2c”);
conn.setRequestProperty(“accept”, “application/json”);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d(“JSON Parser”, “result: ” + result.toString());
} catch (IOException e) {
// e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONArray(result.toString());
} catch (JSONException e) {
Log.e(“JSON Parser”, “Error parsing data ” + e.toString());
}
// return JSON Object
return jObj;
}
}
API URL及其自定义标头:
URL: http://datamall2.mytransport.sg/ltaodataservice/TaxiAvailability
包头中
AccountKey: pVU56+0hI26DNLeTzlU/Dw==
UniqueUserId: 33c07f2f-b4c0-4151-acd3-e0829b303d2c
accept: application/json
EDIT2:我使用它来获取带有自定义标头的原始数据.
http://requestmaker.com/
编辑:这是我得到的JSON.
{
“odata.metadata”: “http://datamall2.mytransport.sg/ltaodataservice/$metadata#TaxiAvailability”,
“value”: [
{
“Longitude”: 103.84009,
“Latitude”: 1.35989
},
{
“Longitude”: 103.84679,
“Latitude”: 1.35544
},
{
“Longitude”: 103.76928,
“Latitude”: 1.4419
}
….
]
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/146231.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...