Reading from URL (GSON)

Sometimes in AEM there can be scenerio where you have to read from 3rd api/url and that data can be used as a dropdown or may be used in your front end sites .

we have to cretae three classes mentioned below .last two classes is just for deserialization of Json.

  • Apireading.java
  • UniverseBean.java
  • Results.java

I have used this “https://swapi.co/api/planets/ url ,which is in json format here I am fetching the data from that url and then converting this json into java object .

code goes like that:

Apireading.java

package amitsample.core.models;
 
import com.google.gson.Gson;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import javax.annotation.PostConstruct;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
 
@Model(adaptables= Resource.class)
 
public class Apireading {
 
    private String finalstring= new String();
    private List<String>planetnamelist;
    private ArrayList<String> residentslist;
    private Results resultsObj;
    private ArrayList<Results> resultsObjlist=new  ArrayList<Results>() ;
 
 
    @PostConstruct
    public void activate() throws Exception {
 
 
        URL url=new URL("https://swapi.co/api/planets/");
        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
        httpsURLConnection.setRequestProperty("Accept", "*/*");
        httpsURLConnection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
        InputStream is=httpsURLConnection.getInputStream();
        InputStreamReader isr=new InputStreamReader (is);
        BufferedReader br = new BufferedReader(isr);
        StringBuilder str=new StringBuilder();
        String line =null;
 
        line=br.readLine();//first time read
         while (line != null){
             str .append(line);//Line will always have something never become null ,but Bufferreader become null after reading the whole so now if we read it again it will be null
             line=br.readLine();//second time reading from bufferreader now bufferreader wont be having any value it would be null
 
        }
 
         finalstring=str.toString();
 
//Dserialization of json
 
        Gson gson=new Gson();
        UniverseBean universeBean=gson.fromJson(finalstring,UniverseBean.class);
       // Results[] results = universeBean.getResults();
        List<Results> results = universeBean.getResults();
        planetnamelist=new ArrayList<String>();
        residentslist=new ArrayList<String>();
        planetnamemethod(results,planetnamelist,residentslist);
 
    }
 
 
    private void planetnamemethod(List<Results> results, List<String> planetnamelist, ArrayList<String> residentslist) {
 
        for (int i=0;i<results.size();i++){
            resultsObj=new Results();
            resultsObj.setName(results.get(i).getName());
            resultsObj.setResidents(results.get(i).getResidents());
            resultsObjlist.add(resultsObj);
 
        }
 
    }
 
 
    public String getFinalstring() {
        return finalstring;
    }
 
    public List<String> getPlanetnamelist() {
        return planetnamelist;
    }
 
    public ArrayList<String> getResidentslist() {
        return residentslist;
    }
 
    public Results getResultsObj() {
        return resultsObj;
    }
 
    public ArrayList<Results> getResultsObjlist() {
        return resultsObjlist;
    }
  
}

UniverseBean.java

package amitsample.core.models;

import com.google.gson.annotations.SerializedName;

import java.util.List;

public class UniverseBean {
    @SerializedName(value = "count")
     private int count;

    @SerializedName(value = "next")
    private String next;

    @SerializedName(value = "previous")
    private String previous;


//    @SerializedName(value = "results")
//    private Results[] results;
//above and below both are correct in context of json  but developer mainly prefer to use list as it has more methods
    @SerializedName(value = "results")
    private List<Results> results;

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public String getNext() {
        return next;
    }

    public void setNext(String next) {
        this.next = next;
    }

    public String getPrevious() {
        return previous;
    }

    public void setPrevious(String previous) {
        this.previous = previous;
    }

    public List<Results> getResults() {
        return results;
    }

    public void setResults(List<Results> results) {
        this.results = results;
    }
}

Results.java

package amitsample.core.models;
 
import com.google.gson.annotations.SerializedName;
 
import java.util.ArrayList;
import java.util.List;
 
public class Results {
    @SerializedName(value = "name")
    private String name;
    @SerializedName(value = "rotation_period")
    private String rotation_period;
    @SerializedName(value = "orbital_period")
    private String orbital_period;
    @SerializedName(value = "diameter")
    private String diameter;
    @SerializedName(value = "climate")
    private String climate;
    @SerializedName(value = "gravity")
    private String gravity;
    @SerializedName(value = "terrain")
    private String terrain;
    @SerializedName(value = "surface_water")
    private String surface_water;
    @SerializedName(value = "population")
    private String population;
//    @SerializedName(value = "residents")
//    private String[] residents;
        @SerializedName(value = "residents")
         private ArrayList<String> residents;
 
    @SerializedName(value = "films")
    private String[] films;
    @SerializedName(value = "created")
    private String created;
    @SerializedName(value = "edited")
    private String edited;
    @SerializedName(value = "url")
    private String url;
 
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getRotation_period() {
        return rotation_period;
    }
 
    public void setRotation_period(String rotation_period) {
        this.rotation_period = rotation_period;
    }
 
    public String getOrbital_period() {
        return orbital_period;
    }
 
    public void setOrbital_period(String orbital_period) {
        this.orbital_period = orbital_period;
    }
 
    public String getDiameter() {
        return diameter;
    }
 
    public void setDiameter(String diameter) {
        this.diameter = diameter;
    }
 
    public String getClimate() {
        return climate;
    }
 
    public void setClimate(String climate) {
        this.climate = climate;
    }
 
    public String getGravity() {
        return gravity;
    }
 
    public void setGravity(String gravity) {
        this.gravity = gravity;
    }
 
    public String getTerrain() {
        return terrain;
    }
 
    public void setTerrain(String terrain) {
        this.terrain = terrain;
    }
 
    public String getSurface_water() {
        return surface_water;
    }
 
    public void setSurface_water(String surface_water) {
        this.surface_water = surface_water;
    }
 
    public String getPopulation() {
        return population;
    }
 
    public void setPopulation(String population) {
        this.population = population;
    }
 
    public ArrayList<String> getResidents() {
        return residents;
    }
 
    public void setResidents(ArrayList<String> residents) {
        this.residents = residents;
    }
 
    public String[] getFilms() {
        return films;
    }
 
    public void setFilms(String[] films) {
        this.films = films;
    }
 
    public String getCreated() {
        return created;
    }
 
    public void setCreated(String created) {
        this.created = created;
    }
 
    public String getEdited() {
        return edited;
    }
 
    public void setEdited(String edited) {
        this.edited = edited;
    }
 
    public String getUrl() {
        return url;
    }
 
    public void setUrl(String url) {
        this.url = url;
    }
}

Now in sightly I have just used and the Apireading model class and and just printed over my browser:

Sightly

<div data-sly-use.search="amitsample.core.models.Apireading">

<b><u><h1 style="color:green">list of planets and their residents =======>>>>>    </h1></u></b>
<ol style="list-style-type:square;" data-sly-list.resultobj=${search.resultsObjlist}>

   <li style="color:red">
       <h2>Planet${resultobjList.index}</h2> <h3>${resultobj.name}</h3>

     <h2>Residentslist of Planet ${resultobjList.index}</h2> 

     <ol data-sly-list=${resultobj.residents}><li>${item}</li></ol>

   </li>
</ol>


</div>

How it will look on page

Share this:

EditReading from url(Gson)

Leave a comment

AmitPandeyblogBlog at WordPress.com.

Published by Amit Pandey

www.m8pandeywrites.wordpress.com

Leave a comment

Design a site like this with WordPress.com
Get started