简体   繁体   中英

Fetching timings info from json using Retrofit

I have some problem fetching info from JSON. I'm confused about whether to use ArrayList or any other data type to retrieve data from JSON server.

I've tried to fetch data using

ArrayList<String>

in model.

Below is data format of JSON

[
   {
    "sun_timing": "{\"sun_from\":\"12:30\",\"sun_to\":\"4:30\"}",
    "mon_timing": "{\"mon_from\":\"3:00\",\"mon_to\":\"4:30\"}"

   },
   {
    "sun_timing": "{\"sun_from\":\"12:30\",\"sun_to\":\"4:30\"}",
    "mon_timing": "{\"mon_from\":\"3:00\",\"mon_to\":\"4:30\"}"

   }
]

I want to fetch all sun_timing data and mon_timing data.

That is sun_from,sun_to and mon_from,mon_to data.

try this out working for me

 private List<String> getSunList() {

    ArrayList sunList = new ArrayList<String>()
    String sun_json = your_json_string
    try {
        JSONObject jsonObject = new JSONObject(sun_json)
        Log.d(TAG, "jsonObject: "+jsonObject)
        Log.d(TAG, "jsonObject: "+sun_json)
        JSONArray jsonArray = jsonObject.getJSONArray("sun_timing")
        for (i in 0 until jsonArray.length())
        {
            JSONObject obj = jsonArray.get(i) as JSONObject
            String sun_from = obj.getString("sun_from")
            String sun_to = obj.getString("sun_to")
            sunList.add(sun_from)
            Log.d(TAG, "obj= "+obj)

        }

    }
    catch (e: java.lang.Exception)
    {

    }

    return sunList
}

Your Plain Old Java Object(POJO) for your json looks like this:

public class Example {

    @SerializedName("sun_timing")
    @Expose
    private String sunTiming;

    @SerializedName("mon_timing")
    @Expose
    private String monTiming;

    public String getSunTiming() {
        return sunTiming;
    }

    public void setSunTiming(String sunTiming) {
        this.sunTiming = sunTiming;
    }

    public String getMonTiming() {
        return monTiming;
    }

    public void setMonTiming(String monTiming) {
        this.monTiming = monTiming;
    }
}

See also: https://stackoverflow.com/a/40973753/10452701 for more details about How to get json via Rerofit2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM