问题描述
- 安卓联网解析长JSON字符串
-
接口地址:http://api.k780.com:88/?app=weather.city&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json代码:
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里面的代码不能用运行
解决方案
先确定后台返回是否正常,内容是否一致,解析用java的JSONObjecct,或者定义一个和json结构一致的类,用谷歌的gson直接解析成类实例
解决方案二:
http://www.zhihu.com/question/23424508
http://www.miui.com/thread-2574889-1-1.html
http://download.csdn.net/detail/yayun0516/8705675
解决方案三:
解析json都是在本地,联网是为了获取json
解决方案四:
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String str = null;
StringBuffer stringBuffer = new StringBuffer();
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
System.out.println(stringBuffer.toString());
return stringBuffer.toString();
}
改成这段代码试一试,你的是获取的json不完整