0

Estoy intentando mostrar en Android Studio un arreglo en jSON. Estoy utilizando la libreria GSON, para que resulte mas sencillo. Pero me he quedado bloqueado o en blanco y no se como seguir avanzado. Extraigo correctamente el primer parametro: geometryType. Pero necesito sacar de la ultima linea del multinivel, los siguiente datos: Country_Region, Last_Update, Confirmed, Deaths y Recovered.

Puedo sacar el primer nivel del JSON, pero ya me pierdo para profundizar en mas niveles. ¿Como es la forma correcta de hacerlo?

JSON

    {  
  "geometryType": "esriGeometryPoint",
  "spatialReference": {
    "wkid": 4326,
    "latestWkid": 4326
  },
  "fields": [
    {
      "name": "OBJECTID",
      "type": "esriFieldTypeOID",
      "alias": "OBJECTID",
      "sqlType": "sqlTypeOther",
      "domain": null,
      "defaultValue": null
    },
    {
      "name": "Province_State",
      "type": "esriFieldTypeString",
      "alias": "Province/State",
      "sqlType": "sqlTypeOther",
      "length": 8000,
      "domain": null,
      "defaultValue": null
    }
  ],
  "features": [   
    {
      "attributes": {
        "OBJECTID": 32,
        "Province_State": "Taiwan",
        "Country_Region": "Taiwan",
        "Last_Update": 1582719784000,
        "Lat": 23.7,
        "Long_": 121,
        "Confirmed": 32,
        "Deaths": 1,
        "Recovered": 5
      }
    },
    {
      "attributes": {
        "OBJECTID": 79,
        "Province_State": null,
        "Country_Region": "Bahrain",
        "Last_Update": 1582656932000,
        "Lat": 26.0275,
        "Long_": 50.55,
        "Confirmed": 23,
        "Deaths": 0,
        "Recovered": 0
      }
    },
    {
      "attributes": {
        "OBJECTID": 18,
        "Province_State": null,
        "Country_Region": "Malaysia",
        "Last_Update": 1582545182000,
        "Lat": 2.5,
        "Long_": 112.5,
        "Confirmed": 22,
        "Deaths": 0,
        "Recovered": 18
      }
    },
    {
      "attributes": {
        "OBJECTID": 90,
        "Province_State": null,
        "Country_Region": "Germany",
        "Last_Update": 1582675389000,
        "Lat": 51,
        "Long_": 9,
        "Confirmed": 18,
        "Deaths": 0,
        "Recovered": 14
      }
    }
  ]
}

Aquí tengo mi Clase: GENERAL_B

public class GENERAL_B{
    private String geometryType;

    public String getGeometryType() {
        return geometryType;
    }
}

MainActivity.JAVA

    public class MainActivity extends AppCompatActivity {

        private Object Attributes;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            //Cargamos Libreria
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
            StrictMode.setThreadPolicy(policy); 
            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url("Mi_URL_AQUI_JSON")
                    .build();
            try {
                Response response = client.newCall(request).execute();
                String json = response.body().string();
                Gson gson = new Gson();

            final GENERAL_B gen = gson.fromJson(json, GENERAL_B.class);
                    Log.d("Mensaje", gen.getGeometryType());


//QUIERO MOSTRAR en un LOG.d: [Country_Region, Last_Update, Confirmed, Deaths y Recovered].

        }catch (IOException e){
                e.printStackTrace();
            }

    }}
1
  • Lo interesante de Gson es que tengas un modelo de datos (Clases) a las que el objeto recibido (JSON) se pueda acoplar. Eso significa que en tu clase debería haber un miembro (features) que sería un List de objetos del tipo attributes. Cuando haces eso y mapeas el JSON a la clase general, ya puedes usar los métodos de esa clase para obtener los datos. La clave es dar coherencia al JSON y al modelo de datos. Mira si esta respuesta te puede ayudar a aclarar el concepto. Si entiendes eso, obtendrás todas las ventajas de Gson.
    – A. Cedano
    el 26 feb. 2020 a las 14:16

2 respuestas 2

1

Las clases necesarias son:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication5;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class EsriGeometryPoint implements Serializable {

    @SerializedName("geometryType")
    @Expose
    private String geometryType;
    @SerializedName("spatialReference")
    @Expose
    private SpatialReference spatialReference;
    @SerializedName("fields")
    @Expose
    private List<Field> fields = new ArrayList<Field>();
    @SerializedName("features")
    @Expose
    private List<Feature> features = new ArrayList<Feature>();
    private final static long serialVersionUID = -57044234498482941L;

    public String getGeometryType() {
        return geometryType;
    }

    public void setGeometryType(String geometryType) {
        this.geometryType = geometryType;
    }

    public SpatialReference getSpatialReference() {
        return spatialReference;
    }

    public void setSpatialReference(SpatialReference spatialReference) {
        this.spatialReference = spatialReference;
    }

    public List<Field> getFields() {
        return fields;
    }

    public void setFields(List<Field> fields) {
        this.fields = fields;
    }

    public List<Feature> getFeatures() {
        return features;
    }

    public void setFeatures(List<Feature> features) {
        this.features = features;
    }

}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication5;

import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Feature implements Serializable {

    @SerializedName("attributes")
    @Expose
    private Attributes attributes;
    private final static long serialVersionUID = 6636177199421449730L;

    public Attributes getAttributes() {
        return attributes;
    }

    public void setAttributes(Attributes attributes) {
        this.attributes = attributes;
    }

}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication5;

import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Attributes implements Serializable {

    @SerializedName("OBJECTID")
    @Expose
    private String oBJECTID;
    @SerializedName("Province_State")
    @Expose
    private Object provinceState;
    @SerializedName("Country_Region")
    @Expose
    private String countryRegion;
    @SerializedName("Last_Update")
    @Expose
    private String lastUpdate;
    @SerializedName("Lat")
    @Expose
    private String lat;
    @SerializedName("Long_")
    @Expose
    private String _long;
    @SerializedName("Confirmed")
    @Expose
    private String confirmed;
    @SerializedName("Deaths")
    @Expose
    private String deaths;
    @SerializedName("Recovered")
    @Expose
    private String recovered;
    private final static long serialVersionUID = 5121520135737124730L;

    public String getOBJECTID() {
        return oBJECTID;
    }

    public void setOBJECTID(String oBJECTID) {
        this.oBJECTID = oBJECTID;
    }

    public Object getProvinceState() {
        return provinceState;
    }

    public void setProvinceState(Object provinceState) {
        this.provinceState = provinceState;
    }

    public String getCountryRegion() {
        return countryRegion;
    }

    public void setCountryRegion(String countryRegion) {
        this.countryRegion = countryRegion;
    }

    public String getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(String lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

    public String getLat() {
        return lat;
    }

    public void setLat(String lat) {
        this.lat = lat;
    }

    public String getLong() {
        return _long;
    }

    public void setLong(String _long) {
        this._long = _long;
    }

    public String getConfirmed() {
        return confirmed;
    }

    public void setConfirmed(String confirmed) {
        this.confirmed = confirmed;
    }

    public String getDeaths() {
        return deaths;
    }

    public void setDeaths(String deaths) {
        this.deaths = deaths;
    }

    public String getRecovered() {
        return recovered;
    }

    public void setRecovered(String recovered) {
        this.recovered = recovered;
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication5;

import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Field implements Serializable {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("alias")
    @Expose
    private String alias;
    @SerializedName("sqlType")
    @Expose
    private String sqlType;
    @SerializedName("domain")
    @Expose
    private Object domain;
    @SerializedName("defaultValue")
    @Expose
    private Object defaultValue;
    @SerializedName("length")
    @Expose
    private int length;
    private final static long serialVersionUID = -6311716224407000787L;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    public String getSqlType() {
        return sqlType;
    }

    public void setSqlType(String sqlType) {
        this.sqlType = sqlType;
    }

    public Object getDomain() {
        return domain;
    }

    public void setDomain(Object domain) {
        this.domain = domain;
    }

    public Object getDefaultValue() {
        return defaultValue;
    }

    public void setDefaultValue(Object defaultValue) {
        this.defaultValue = defaultValue;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication5;

import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class SpatialReference implements Serializable {

    @SerializedName("wkid")
    @Expose
    private int wkid;
    @SerializedName("latestWkid")
    @Expose
    private int latestWkid;
    private final static long serialVersionUID = -5304181045052712104L;

    public int getWkid() {
        return wkid;
    }

    public void setWkid(int wkid) {
        this.wkid = wkid;
    }

    public int getLatestWkid() {
        return latestWkid;
    }

    public void setLatestWkid(int latestWkid) {
        this.latestWkid = latestWkid;
    }
}

Y en este caso he creado un main para testearlo. Aquí el ejemplo:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication5;

import com.google.gson.Gson;

/**
 *
 * @author fernando.alvarez
 */
public class Test {

    public static void main(String[] args) {


        String json = "{\"geometryType\":\"esriGeometryPoint\",\"spatialReference\":{\"wkid\":4326,\"latestWkid\":4326},\"fields\":[{\"name\":\"OBJECTID\",\"type\":\"esriFieldTypeOID\",\"alias\":\"OBJECTID\",\"sqlType\":\"sqlTypeOther\",\"domain\":null,\"defaultValue\":null},{\"name\":\"Province_State\",\"type\":\"esriFieldTypeString\",\"alias\":\"Province/State\",\"sqlType\":\"sqlTypeOther\",\"length\":8000,\"domain\":null,\"defaultValue\":null}],\"features\":[{\"attributes\":{\"OBJECTID\":32,\"Province_State\":\"Taiwan\",\"Country_Region\":\"Taiwan\",\"Last_Update\":1582719784000,\"Lat\":23.7,\"Long_\":121,\"Confirmed\":32,\"Deaths\":1,\"Recovered\":5}},{\"attributes\":{\"OBJECTID\":79,\"Province_State\":null,\"Country_Region\":\"Bahrain\",\"Last_Update\":1582656932000,\"Lat\":26.0275,\"Long_\":50.55,\"Confirmed\":23,\"Deaths\":0,\"Recovered\":0}},{\"attributes\":{\"OBJECTID\":18,\"Province_State\":null,\"Country_Region\":\"Malaysia\",\"Last_Update\":1582545182000,\"Lat\":2.5,\"Long_\":112.5,\"Confirmed\":22,\"Deaths\":0,\"Recovered\":18}},{\"attributes\":{\"OBJECTID\":90,\"Province_State\":null,\"Country_Region\":\"Germany\",\"Last_Update\":1582675389000,\"Lat\":51,\"Long_\":9,\"Confirmed\":18,\"Deaths\":0,\"Recovered\":14}}]}";
        Gson gson = new Gson();
        EsriGeometryPoint prueba = gson.fromJson(json, EsriGeometryPoint.class);        
        for(Feature r: prueba.getFeatures()){
            System.out.println(r.getAttributes().getLong());
        }


    }

}

El objeto EsriGeometryPoint sera un objecto con la estructura del Json. Bastará recorrerlo para obtener la información necesaria.

El Output es:

121
50.55
112.5
9

Las clases las cree Aqui

0

Te dejo los objetos creados a partir de ese json.

Puedes usar esta pagina para convertir un json a una clase.

http://json2csharp.com/#

public class SpatialReference
{
    public int wkid { get; set; }
    public int latestWkid { get; set; }
}

public class Field
{
    public string name { get; set; }
    public string type { get; set; }
    public string alias { get; set; }
    public string sqlType { get; set; }
    public object domain { get; set; }
    public object defaultValue { get; set; }
    public int? length { get; set; }
}

public class Attributes
{
    public int OBJECTID { get; set; }
    public string Province_State { get; set; }
    public string Country_Region { get; set; }
    public object Last_Update { get; set; }
    public double Lat { get; set; }
    public double Long_ { get; set; }
    public int Confirmed { get; set; }
    public int Deaths { get; set; }
    public int Recovered { get; set; }
}

public class Feature
{
    public Attributes attributes { get; set; }
}

public class RootObject
{
    public string geometryType { get; set; }
    public SpatialReference spatialReference { get; set; }
    public List<Field> fields { get; set; }
    public List<Feature> features { get; set; }
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.