gpt4 book ai didi

java - 为什么我会收到 Json Malformed Exception

转载 作者:行者123 更新时间:2023-12-01 19:51:09 28 4
gpt4 key购买 nike

我有一个 Android 应用程序,它在后台执行一些网络处理,从 https://ipinfo.io/json 处的 json api 请求信息。 。 bufferReader httpConnection 已成功创建,并且 BufferReader 包含我稍后添加到输出字符串(while 循环)中的信息。

现在转换成json对象时..

String INTERNET_IP_SOURCE = "https://ipinfo.io/json"

是全局声明。我收到有关格式错误的 json 对象的异常。我在这里缺少什么?谢谢!

private class TaskPublicNet extends AsyncTask<Void, String, Void> {
String output = "";
int progress = 0;
String json = "";
//only 7 lines of information for public ip info (set progress at 5)
final static int PROGRESS_MAX = 5;
String[] iface;

@Override
protected void onPreExecute() {
progressBar.setMax(PROGRESS_MAX);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(1);
}

@Override
protected void onPostExecute(Void aVoid) {
progressBar.setProgress(5);
Log.v("ALL ", localIfaceInfo.toString());
}

@Override
protected void onProgressUpdate(String... values) {
Log.v("PROGRESS ", values[0]);
localIfaceInfo.add(values[0]);
localNetAdapter.notifyDataSetInvalidated();
}

@Override
protected Void doInBackground(Void... params) {

/** Getting public interface information*/
try {
// Make a URL to the web page
URL url = new URL(INTERNET_IP_SOURCE);
// Get the input stream through URL Connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
// read each line and write to System.out
while ((line = bf.readLine()) != null) {
Log.v("LINE ", line);
output += line;
}
bf.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}

//json parsing
try {

JSONArray ja = new JSONArray(output);
JSONObject jo = (JSONObject) ja.get(0);
String publicIp = jo.get("ip").toString();
String city = jo.get("city").toString();
String provider = jo.get("org").toString();
Log.v("PUBLIC ", publicIp +" "+city+" "+provider);
publishProgress("Public Ip: "+publicIp);
publishProgress("City: "+city);
publishProgress("Provider: "+provider);
}
catch (JSONException ex){
ex.printStackTrace();
}
return null;
}
}

最佳答案

响应看起来像这样

{
"ip": "XXXXXX",
"city": "",
"region": "",
"country": "XX",
"loc": "XXXXX,XXXXX",
"org": "XXXXXXXX"
}

但是在你的代码中你正在这样做

 JSONArray ja = new JSONArray(output);
JSONObject jo = (JSONObject) ja.get(0);

json 是一个对象而不是数组。尝试直接将其解析为对象

JSONObject jo = new JSONObject(output)

关于java - 为什么我会收到 Json Malformed Exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51312932/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com