如何使用Retrofit解析嵌套的json?

时间:2018-02-05 12:17:07

标签: java android json retrofit

我想使用retrofit解析嵌套的json并将其绑定在recyclerview中。熟悉使用Retrofit解析简单的json 。但我不知道如何解析嵌套json使用改造。我是改造的新手。任何帮助将不胜感激?

以下是链接:http://api.wunderground.com/api/356d60036a9374e9/conditions/forecast/alert/q/22.897,88.879.json

JSON DATA:

tOracleInput

在那个json数据中,我想获取以下json数据:

{
  "response": {
  "version":"0.1",
  "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
  "features": {
  "conditions": 1
  ,
  "forecast": 1
  }
        ,
    "error": {
        "type": "unknownfeature"
    }
    }
  , "current_observation": {
        "image": {
        "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",
        "title":"Weather Underground",
        "link":"http://www.wunderground.com"
        },
        "display_location": {
        "full":"Tentulbaria, India",
        "city":"Tentulbaria",
        "state":"WB",
        "state_name":"India",
        "country":"IN",
        "country_iso3166":"IN",
        "zip":"00000",
        "magic":"608",
        "wmo":"41946",
        "latitude":"22.890000",
        "longitude":"88.870000",
        "elevation":"11.9"
        },
        "observation_location": {
        "full":"Kolkata, ",
        "city":"Kolkata",
        "state":"",
        "country":"IN",
        "country_iso3166":"IN",
        "latitude":"22.64999962",
        "longitude":"88.44999695",
        "elevation":"20 ft"
        },
        "estimated": {
        },
        "station_id":"VECC",
        "observation_time":"Last Updated on February 5, 5:30 PM IST",
        "observation_time_rfc822":"Mon, 05 Feb 2018 17:30:00 +0530",
        "observation_epoch":"1517832000",
        "local_time_rfc822":"Mon, 05 Feb 2018 17:44:32 +0530",
        "local_epoch":"1517832872",
        "local_tz_short":"IST",
        "local_tz_long":"Asia/Kolkata",
        "local_tz_offset":"+0530",
        "weather":"Clear",
        "temperature_string":"81 F (27 C)",
        "temp_f":81,
        "temp_c":27,
        "relative_humidity":"61%",
        "wind_string":"Calm",
        "wind_dir":"North",
        "wind_degrees":0,
        "wind_mph":0,
        "wind_gust_mph":0,
        "wind_kph":0,
        "wind_gust_kph":0,
        "pressure_mb":"1013",
        "pressure_in":"29.92",
        "pressure_trend":"0",
        "dewpoint_string":"66 F (19 C)",
        "dewpoint_f":66,
        "dewpoint_c":19,
        "heat_index_string":"83 F (28 C)",
        "heat_index_f":83,
        "heat_index_c":28,
        "windchill_string":"NA",
        "windchill_f":"NA",
        "windchill_c":"NA",
        "feelslike_string":"83 F (28 C)",
        "feelslike_f":"83",
        "feelslike_c":"28",
        "visibility_mi":"1.7",
        "visibility_km":"2.8",
        "solarradiation":"--",
        "UV":"-1","precip_1hr_string":"-9999.00 in (-9999.00 mm)",
        "precip_1hr_in":"-9999.00",
        "precip_1hr_metric":"--",
        "precip_today_string":"0.00 in (0.0 mm)",
        "precip_today_in":"0.00",
        "precip_today_metric":"0.0",
        "icon":"clear",
        "icon_url":"http://icons.wxug.com/i/c/k/nt_clear.gif",
        "forecast_url":"http://www.wunderground.com/global/stations/41946.html",
        "history_url":"http://www.wunderground.com/history/airport/VECC/2018/2/5/DailyHistory.html",
        "ob_url":"http://www.wunderground.com/cgi-bin/findweather/getForecast?query=22.64999962,88.44999695",
        "nowcast":""
    }
}

4 个答案:

答案 0 :(得分:0)

您可以将json转换器添加到Retrofit,然后您可以解析它。

Parsing Nested Json

直到现在我已经找到的改进最佳教程。

Retrofit complete turoial

这将帮助您解决与Retrofit相关的所有问题。

答案 1 :(得分:0)

像这样创建模式,在你的响应类型中传递模型,它会自动将json解析为图像数据模型

 public class Example {

 @SerializedName("current_observation")
 @Expose
 private CurrentObservation currentObservation;

 public CurrentObservation getCurrentObservation() {
 return currentObservation;
 }

 public void setCurrentObservation(CurrentObservation currentObservation) {
 this.currentObservation = currentObservation;
 }

 public static class CurrentObservation {

    @SerializedName("image")
    @Expose
    private Image image;

    public Image getImage() {
    return image;
    }

    public void setImage(Image image) {
    this.image = image;
    }
 }

 public static class Image {

        @SerializedName("url")
        @Expose
        private String url;
        @SerializedName("title")
        @Expose
        private String title;
        @SerializedName("link")
        @Expose
        private String link;

        public String getUrl() {
        return url;
        }

        public void setUrl(String url) {
        this.url = url;
        }

        public String getTitle() {
        return title;
        }

        public void setTitle(String title) {
        this.title = title;
        }

        public String getLink() {
        return link;
        }

        public void setLink(String link) {
        this.link = link;
        }

  }

}

示例api调用

  public interface Service {
  @GET("users/info")
  Call<Example> getInfo();
}

修改 您可以在MainActivity中的任何位置调用此改装功能并使用数据。

public void getImageData(){

Call<Example> call = apiService.getInfo();
call.enqueue(new Callback<Example>() {
  @Override
  public void onResponse(Call<Example> call, Response<Example> response) {
      //this is how you can use the parsed model
      Example info = response.body();
  }

  @Override
  public void onFailure(Call<Example> call, Throwable t) {
      //handle the error here
  }

}

答案 2 :(得分:0)

首先,创建Model,即POJO类来解析您的回复

它看起来像这样

package app.com.socket;
/**
 * Created by akshay.katariya on 05-Feb-18.
 */

import com.google.gson.annotations.SerializedName;

public class Pojo
{

    @SerializedName("response")
    public Response response;
    @SerializedName("current_observation")
    public Current_observation current_observation;

    public static class Features {
        @SerializedName("conditions")
        public int conditions;
        @SerializedName("forecast")
        public int forecast;
    }

    public static class Error {
        @SerializedName("type")
        public String type;
    }

    public static class Response {
        @SerializedName("version")
        public String version;
        @SerializedName("termsofService")
        public String termsofService;
        @SerializedName("features")
        public Features features;
        @SerializedName("error")
        public java.lang.Error error;
    }

    public static class Image {
        @SerializedName("url")
        public String url;
        @SerializedName("title")
        public String title;
        @SerializedName("link")
        public String link;
    }

    public static class Display_location {
        @SerializedName("full")
        public String full;
        @SerializedName("elevation")
        public String elevation;
    }

    public static class Observation_location {
        @SerializedName("elevation")
        public String elevation;
    }

    public static class Estimated {
    }

    public static class Current_observation {
        @SerializedName("image")
        public Image image;
        @SerializedName("display_location")
        public Display_location display_location;
        @SerializedName("observation_location")
        public Observation_location observation_location;
        @SerializedName("estimated")
        public Estimated estimated;
        @SerializedName("nowcast")
        public String nowcast;

        public Image getImage() {
            return image;
        }

        public void setImage(Image image) {
            this.image = image;
        }

        public Display_location getDisplay_location() {
            return display_location;
        }

        public void setDisplay_location(Display_location display_location) {
            this.display_location = display_location;
        }

        public Observation_location getObservation_location() {
            return observation_location;
        }

        public void setObservation_location(Observation_location observation_location) {
            this.observation_location = observation_location;
        }

        public Estimated getEstimated() {
            return estimated;
        }

        public void setEstimated(Estimated estimated) {
            this.estimated = estimated;
        }

        public String getNowcast() {
            return nowcast;
        }

        public void setNowcast(String nowcast) {
            this.nowcast = nowcast;
        }
    }

    public Response getResponse() {
        return response;
    }

    public void setResponse(Response response) {
        this.response = response;
    }

    public Current_observation getCurrent_observation() {
        return current_observation;
    }

    public void setCurrent_observation(Current_observation current_observation) {
        this.current_observation = current_observation;
    }
}

产生适当的吸气剂&amp;设定器

然后在你的主类创建

Pojo model = new Pojo(); 

致电API&amp;解析响应

model = response.body(); // retrofit api call parsing

您已准备好设置所有值

mEditText.setText(model.getCurrent_observation().image.url);

答案 3 :(得分:0)

简单的方法是接收响应作为JsonObject / JsonArray并解析它以使用您自己的Model类创建对象。

因此,您可以避免不需要的数据,是的,您的代码将是冗长但值得。您可以格式化和存储数据。易于显示。

另外&#34;选择&#34;可以使用方法代替&#34; Get&#34;,因此可以避免使用NULL。