Java - Leer un valor en concreto de JSON en Java

 
Vista:

Leer un valor en concreto de JSON en Java

Publicado por Draki00 (1 intervención) el 22/10/2022 22:57:52
Estoy haciendo una app en android studio utilizando una API que devuelve lo siguiente:

1
2
3
4
5
6
7
8
9
10
[
{
"domains": ["upes.ac.in"],
"country": "India",
"state-province": "Dehradun",
"web_pages": ["https://www.upes.ac.in/"],
"name": "University of Petroleum and Energy Studies",
"alpha_two_code": "IN"
}
]

Lo recorro de la siguiente manera:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public void onResponse(String response) {
            listaUniversidades = new ArrayList<>();
                JSONArray jsonArray = new JSONArray(response);
 
                String nombreUni, pais, url;
 
                for (int i = 0; i < jsonArray.length(); i++) {
 
                    nombreUni = jsonArray.getJSONObject(i).getString("name");
                    pais = jsonArray.getJSONObject(i).getString("country");
                    url = jsonArray.getJSONObject(i).getString("web_pages"));
 
                    texto.setText(url);
 
                    listaUniversidades.add(new Universidad(nombreUni, pais, url));
                }
}

La cosa es que el web_pages me devuelve lo siguiente:
1
["http://.www.upes.ac.in/"]

Como podría hacer para que me devuelva la url bien? Ya que de esa forma no puedo acceder a la web de la universidad.

Gracias!
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Billy Joel
Val: 2.665
Oro
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Leer un valor en concreto de JSON en Java

Publicado por Billy Joel (876 intervenciones) el 23/10/2022 01:47:12
Veo que intentas transformar el Json a un objeto de tipo Universidad.
Yo la definí así:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import java.util.List;
import org.apache.commons.lang3.ObjectUtils;
 
/**
 *
 * @author Billy Joel Johnson
 */
public class Universidad {
 
    private String name;
    private String stateProvince;
    private String alphaTwoCode;
    private List<String> domains;
    private List<String> webPages;
 
    public Universidad(String name, String stateProvince, String alphaTwoCode, List<String> domains, List<String> webPages) {
        this.name = name;
        this.stateProvince = stateProvince;
        this.alphaTwoCode = alphaTwoCode;
        this.domains = domains;
        this.webPages = webPages;
    }
 
    public Universidad(String name, String stateProvince, List<String> webPages) {
        this.name = name;
        this.stateProvince = stateProvince;
        this.webPages = webPages;
        domains = null;
        alphaTwoCode = null;
    }
 
    public Universidad() {
        name = null;
        stateProvince = null;
        alphaTwoCode = null;
        domains = null;
        webPages = null;
    }
 
    @Override
    public String toString() {
        return "name: " + name
                + "\nstateProvince: " + stateProvince
                + "\nalphaTwoCode: " + alphaTwoCode
                + "\ndomains: " + (ObjectUtils.isEmpty(domains) ? "null" : domains.toString())
                + "\nwebPages: " + (ObjectUtils.isEmpty(webPages) ? "null" : webPages.toString());
    }
 
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
 
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
 
    /**
     * @return the stateProvince
     */
    public String getStateProvince() {
        return stateProvince;
    }
 
    /**
     * @param stateProvince the stateProvince to set
     */
    public void setStateProvince(String stateProvince) {
        this.stateProvince = stateProvince;
    }
 
    /**
     * @return the alphaTwoCode
     */
    public String getAlphaTwoCode() {
        return alphaTwoCode;
    }
 
    /**
     * @param alphaTwoCode the alphaTwoCode to set
     */
    public void setAlphaTwoCode(String alphaTwoCode) {
        this.alphaTwoCode = alphaTwoCode;
    }
 
    /**
     * @return the domains
     */
    public List<String> getDomains() {
        return domains;
    }
 
    /**
     * @param domains the domains to set
     */
    public void setDomains(List<String> domains) {
        this.domains = domains;
    }
 
    /**
     * @return the webPages
     */
    public List<String> getWebPages() {
        return webPages;
    }
 
    /**
     * @param webPages the webPages to set
     */
    public void setWebPages(List<String> webPages) {
        this.webPages = webPages;
    }
}

Trabajar con objeto de tipo JSONArray es como trabajar con un List<Object> y por la forma en la que el JSonObject está definido entiendo que la universidad puede tener más de un "web_page" y más de un "domains". Entonces tu objeto Universidad debería estar preparado para eso.

El resto del código lo resuelvo así:
1
2
3
4
5
6
7
8
9
10
JSONArray jsonArray = buildResponse(source);
jsonArray.forEach(o -> {
    JSONObject u = (JSONObject) o;
    List<String> webPages = new ArrayList<>();
    for (Object w : u.getJSONArray("web_pages")) {
        webPages.add(w.toString());
    }
    listaUniversidades.add(new Universidad(u.getString("name"), u.getString("country"), webPages));
});
System.out.println("Lista: " + listaUniversidades);

Cualquier duda solo grita.

Saludos,
Billy Joel
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar