当前位置: 代码迷 >> Android >> 安卓从K780的天气城市代码接口解析JSON字符串的有关问题
  详细解决方案

安卓从K780的天气城市代码接口解析JSON字符串的有关问题

热度:93   发布时间:2016-04-27 22:20:44.0
安卓从K780的天气城市代码接口解析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<City> getlist(String cityjson)
{

Log.i("==========", "getlist方法");
try
{
ArrayList<City> list = new ArrayList<City>();
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里面的代码不能用运行
 
------解决思路----------------------
解析出来了,里面是没有json数组的
public ArrayList<City> getlist(String cityjson) {

        ArrayList<City> c3 = new ArrayList<>();
        Log.i("==========", "getlist方法");
        try {
            JSONObject ob = new JSONObject(cityjson);
            JSONObject object = ob.getJSONObject("result");
            for (int j = 1; j <= 2646; j++) {
                JSONObject wea = object.optJSONObject(String.valueOf(j));
//                JSONObject wea = array.getJSONObject(i);
                if (wea!=null){
                    String name = wea.getString("citynm");
                    String key = wea.getString("weaid");
                    c3.add(new City(name, key));
                    Log.i("========", name);
                }
            }
            return c3;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


大爷,有空来玩啊~sumile.cn
  相关解决方案