代码:
package com.example.cityinfo;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JsonUtils
{
//cityjson是从网络获取的json字符串
public ArrayList getlist(String cityjson)
{
Log.i("==========", "getlist方法");
try
{
ArrayList list = new ArrayList();
JSONObject object = new JSONObject(cityjson);
JSONArray array = object.getJSONArray("result");
for(int i=0;i<array.length();i++)
{
JSONObject wea = array.getJSONObject(i);
String name =wea.getString("citynm");
String key = wea.getString("weaid");
list.add(new City(name,key));
Log.i("========", name);
}
return list;
} catch (JSONException e)
{
}
return null;
}
}
获取json字符串代码
package com.example.cityinfo;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
public class HttpUtils
{
public String getJson(String cityURL)
{
try
{
Log.i("======", "正在连接。。。");
HttpURLConnection conn=(HttpURLConnection)new URL(cityURL).openConnection();
conn.setRequestMethod("GET");
conn.connect();
if(conn.getResponseCode() == 200)
{
Log.i("=====", "连接成功。。。");
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int num=0;
StringBuffer buffer = new StringBuffer();
while ((num=is.read(b))!=-1)
{
buffer.append(new String(b,0,num));
}
return buffer.toString();
}
} catch (MalformedURLException e)
{
} catch (IOException e)
{
}
return null;
}
}
为什么解析不了,还有每次获取的json字符串长度都不一样。
解析里的try里面的代码不能用运行