使用OpenWeatherMap API时出现此异常错误。我只是试图让结果成为JSONObject,但 null 不断出现。
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// What's coming in as result...
// Printed to the console...
// null{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":800,"main":"Clear",
// "description":"clear sky","icon":"01d"}],...}
try {
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather Info", weatherInfo);
} catch (JSONException e) {
e.printStackTrace();
}
}
JSON数据很好但我想要的只是它成为一个JSONObject但是null部分正在捕获。任何想法为什么会发生这种情况?
同样来自JSON Response
的网站是:
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],.....}
为什么一开始就没有空? 谢谢你的帮助。
答案 0 :(得分:6)
您收到的数据天气是JSONArray。
试试这个:
String json = "{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01d\"}],.....}";
try{
JSONObject jo = new JSONObject(json);
JSONArray weather = jo.getJSONArray("weather");
for(int i = 0;i < weather.length(); i++){
JSONObject w = weather.getJSONObject(i);
String main = w.getString("main");
String description = w.getString("description");
//...
}
}catch (Exception e){
}
正如您所说,如果服务器返回的结果以null
开头,您将遇到此异常org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
。
这是因为此结果不是有效的JSON内容。
如果您确实从服务器收到此无效内容,则解决方法可能是在解析JSON之前删除null
。
String crappyPrefix = "null";
if(result.startsWith(crappyPrefix)){
result = result.substring(crappyPrefix.length(), result.length());
}
JSONObject jo = new JSONObject(result);
答案 1 :(得分:3)
试试这个(为我工作)..我遇到了同样的问题
public class DownloadData extends AsyncTask<String , Void, String >{
HttpURLConnection httpURLConnection =null;
URL url;
String resultString=""; <------- instead of setting it to null
@Override
protected String doInBackground(String... urls) {
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while(data != -1){
char ch = (char) data;
resultString += ch;
data = isr.read();
}
return resultString;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
答案 2 :(得分:1)
试试这个,
JSONObject jsonObject = new JSONObject(result);
try {
JSONArray jsonArray = jsonObject.getJSONArray("weather");
for(int i=0;i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String main =object.getString("main");
}
} catch (JSONException e) {
e.printStackTrace();
}
答案 3 :(得分:1)
有时候问题是您的响应为null,但是您希望使用JSONObject。 最好在服务器端解决该问题。如果您无法编辑服务器端代码,则this question和this one可能会有用
答案 4 :(得分:0)
错误表示您的JSON无效 probabaly
您可以测试您的JSON格式here。
但是代码中的问题是你试图在这里使用getString()
String weatherInfo = jsonObject.getString("weather");
虽然天气实际上是JSONArray,但如果你想将它作为字符串使用
String weatherInfo = jsonObject.getJSONArray("weather").toString();
答案 5 :(得分:0)
成员变量默认情况下被初始化,
如果是String,它将初始化为null
即。撰写String xyz;
等同于String xyz=null;
当我们将此空字符串连接到另一个字符串时,java编译器将空值设置为字符串
即。 xyz=xyz+"abc"; //would result as nullabc
这就是您的JSON数据所发生的事情,您通过字符串获取的数据运行良好,但是当您将其作为JSON对象放置时,它将返回异常
"Value null of type org.json.JSONObject$1 cannot be converted to JSONObject"
,因为它将其视为空值。
最好将字符串初始化为空字符串,即。
String xyz="";
或者您也可以将字符串开头的null删除为
if(result.startsWith(“ null”)){ 结果= result.substring(“ null” .length(),result.length()); } JSONObject json =新的JSONObject(result);
答案 6 :(得分:-1)
尝试以下代码,它为我工作。
JSONParser jParser = new JSONParser();
JSONObject weatherUrlObject =jParser.getJSONFromUrl(weatherUrl);
try {
JSONArray weather = weatherUrlObject.getJSONArray("weather");
WeatherNow.setWeather_id(weather.getJSONObject(0).getString("id").toString());
WeatherNow.setWeather_main(weather.getJSONObject(0).getString("main").toString());
WeatherNow.setWeather_description(weather.getJSONObject(0).getString("description").toString());
WeatherNow.setWeather_icon(weather.getJSONObject(0).getString("icon").toString());
} catch (Exception e) {
e.printStackTrace();
}
JSONPaser Class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
WeatherNow是我的Getter-Setter方法。