当前位置: 首页 > 知识库问答 >
问题:

用凌空和GSON解析JSON

闾丘卓
2023-03-14

我正在尝试从此网址解析 json

http://api.openweathermap.org/data/2.5/forecast/daily?q=09100

我为gson创建了pojo,并在我的应用程序中添加了基于截击的类。

我想使用自定义适配器将 json 对象解析到我的列表视图中

我的截击Gson请求:

  private void loadAPI(){
        mRequestQueue = Volley.newRequestQueue(getActivity());

        String url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=09100&mode=json&units=metric&cnt=7&lang=tr";
        //showDialog();
        GsonRequest<WeatherItem> myReq = new GsonRequest<WeatherItem>(
                Request.Method.GET,
                url,
                WeatherItem.class,
                mOnWeatherResponseLister(),
                mOnErrorListener());


        mRequestQueue.add(myReq);

    }

    private Response.Listener<WeatherItem> mOnWeatherResponseLister() {
  ForecastFragment 108 =  return new Response.Listener<WeatherItem>() {
            @Override
            public void onResponse(WeatherItem response) {
                try {
                    Log.d("Json Response", response.list.toString());
                    Log.d("Json Response", response.list.get(0).dt.toString());
                    Log.d("Json Response", response.list.get(0).weather.get(0).description.toString());
                    Log.d("Json Response",WeatherUtility.formatMinTemperature(getActivity(),response.list.get(0).temp.min));
                    for (int i = 0; i<=response.list.size()-1 ; i++) {


                        WeatherResp weatherResp = new WeatherResp();
                        Weather weather= new Weather();
                          weatherResp.weather.set(i,weather).setIcon(WeatherUtility.getIconResourceForWeatherCondition(response.list.get(i).weather.get(i).id));
                Fragment 121 = weatherResp.setDt((response.list.get(i).dt));
                          weatherResp.weather.set(i,weather).setDescription(response.list.get(i).weather.get(i).description.toString());
                          weatherResp.temp.setMin(Double.valueOf(WeatherUtility.formatMinTemperature(getActivity(), response.list.get(i).temp.min)));
                          weatherResp.temp.setMax(Double.valueOf(WeatherUtility.formatMaxTemperature(getActivity(), response.list.get(i).temp.max)));

                        arrItemList.add(weatherResp);
                    }

                    mListView.setAdapter(mForecastAdapter);
                    mForecastAdapter.notifyDataSetChanged();


                } catch (Exception e) {
                    e.printStackTrace();
                }
                //hideDialog();
            }

            ;
        };
    }

波霍斯:

public class WeatherItem {

    public String cod;
    public String message;
    public int cnt;
    public ArrayList<WeatherResp> list;
    public String getCod() {
        return cod;
    }

public class WeatherResp {

    public Long dt;
    public Temp temp;
    public Float pressure;
    public Integer humidity;
    public ArrayList<Weather> weather;
    public Float speed;
    public Float deg;
    public Integer clouds;

public class Weather {

    public Integer id;
    public String main;
    public String description;
    public int icon;
public class Temp {


    public Float day;
    public Double min;
    public Double max;
    public Double night;
    public Double eve;
    public Double morn;

我的适配器:

public class WeatherAdapter extends BaseAdapter {


private Context ctx;
private ArrayList<WeatherItem> weatherItems;
private ArrayList<WeatherResp> arrItemList;

public WeatherAdapter(Context ctx, ArrayList<WeatherResp> weatherResps) {

    this.ctx = ctx;
    this.arrItemList = weatherResps;
}

public static class ViewHolder {
    public ImageView iconView;
    public TextView dateView;
    public TextView descriptionView;
    public TextView highTempView;
    public TextView lowTempView;
    //public TextView humidity;
    //public TextView pressure;


    public ViewHolder(View v) {
        iconView = (ImageView) v.findViewById(R.id.list_item_icon);
        dateView = (TextView) v.findViewById(R.id.list_item_date_textview);
        descriptionView = (TextView) v.findViewById(R.id.list_item_forecast_textview);
        highTempView = (TextView) v.findViewById(R.id.list_item_high_textview);
        lowTempView = (TextView) v.findViewById(R.id.list_item_low_textview);

        v.setTag(this);
    }
}

/**
 * Cache of the children views for a forecast list item.
 */
@Override
public int getCount() {
    return weatherItems.size();

}

@Override
public Object getItem(int i) {
    return weatherItems.get(i);
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int position, View convertview, ViewGroup viewGroup) {

    ViewHolder holder;
    View v = convertview;

    if (v == null) {
        v = View.inflate(ctx, R.layout.list_items_forecast, viewGroup);
        holder = new ViewHolder(v);
        holder.iconView = (ImageView) v.findViewById(R.id.list_item_icon);
        holder.dateView = (TextView) v.findViewById(R.id.list_item_date_textview);
        holder.descriptionView = (TextView) v.findViewById(R.id.list_item_forecast_textview);
        holder.lowTempView = (TextView) v.findViewById(R.id.list_item_low_textview);
        holder.highTempView = (TextView) v.findViewById(R.id.list_item_high_textview);
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }

    WeatherResp weatherResp1 = arrItemList.get(position);

    holder.iconView.setImageResource(weatherResp1.getWeather().get(position).getIcon());
    holder.dateView.setText(weatherResp1.getDt().toString());
    holder.descriptionView.setText(weatherResp1.getWeather().get(position).getDescription());
    holder.lowTempView.setText(WeatherUtility.formatMinTemperature(ctx, weatherResp1.getTemp().min));
    holder.highTempView.setText(WeatherUtility.formatMaxTemperature(ctx,weatherResp1.getTemp().max));
    return v;
}

当我运行我的logcat是:

W/System.err﹕ java.lang.NullPointerException
W/System.err﹕ at com.hasan.basan.fragment.ForecastFragment$1.onResponse(ForecastFragment.java:121)
W/System.err﹕ at com.hasan.basanfragment.ForecastFragment$1.onResponse(ForecastFragment.java:108)
W/System.err﹕ at com.hasan.basan.utility.GsonRequest.deliverResponse(GsonRequest.java:78)
W/System.err﹕ at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:725)
W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:92)
W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5041)
W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)

我的错在哪里?先谢谢你

共有1个答案

冉子石
2023-03-14

您的异常是从这里抛出的:< code > com . Hasan . basan . fragment . forecast fragment $ 1 . on response(forecast fragment . Java:121)我看不到行号,所以我将尝试猜测抛出异常的原因。

WeatherResp weatherResp = new WeatherResp();
Weather weather= new Weather();
weatherResp.weather.set(i,weather).setIcon(WeatherUtility.getIconResourceForWeatherCondition(response.list.get(i).weather.get(i).id));

在第3行代码中,您正在访问变量be < code > weather resp . weather 。我有两种解释。

>

  • 可能您忘记将新的<code>Weather

    可能您忘记在<code>WeatherResp变量的<code>ArrayList

  •  类似资料:
    • 如何使用GSON解析这个json? 我的代码: 我的stacktrace com.google.gson.JsonSyn出租车异常:java.lang.IllegalStateExctive:预期BEGIN_OBJECT但BEGIN_ARRAY在第1行第2列路径$com.google.gson.internal.bind.ReflecteTypeAdapterFactory$Adapter.rea

    • 问题内容: 我在解析从javascript获取的JSON时遇到问题。JSON的格式是这样的: 到目前为止,我已经能够做到这一点: 但是我现在还需要用这些位置创建一个类。我一直在上课,因为我先尝试打印输出,但是我无法进一步细分它。我收到此错误消息: java.lang.IllegalStateException:这不是JSON数组。 我的代码是这样的: 我也尝试过这种方式: 在这种情况下,我得到:

    • 我正在使用凌空OkHttp从服务器获取一些数据。 响应是一个包含JSON的字符串,我想使用GSON/POJO解析它。 我得到错误: 预期BEGIN_OBJECT,但在第1行第1列路径$上是STRING 尝试解析时。 原因:java.lang.IllegalStateException:预期BEGIN_OBJECT但在第1行第1列路径$ com.google.gson.stream.JsonRead

    • 我使用的是volley.jar,在编译时没有错误,但是有运行时异常。 然后添加volley.jar和build path。什么是问题? CustomAdapter.java