JSON
qué es JSON
Ejemplo:
| xml | json |
<listado>
<persona>
<nombre>Juan</nombre>
<apellidos>Palomo</apellidos>
<fecha>20/10/1980</fecha>
</persona>
<persona>
<nombre>Pepe</nombre>
<apellidos>Gotera</apellidos>
<fecha>7/8/1990</fecha>
</persona>
</listado>
|
{"listado": [
{
"nombre":"Juan",
"apellidos":"Palomo",
"fecha": "20/10/1980"
},
{
"nombre": "Pepe",
"apellidos": "Gotera",
"fecha": "7/8/1990"
}
]
}
|
Ejemplo: repositorios de un usuario en GitHub
https://api.github.com/users/paco-portada/repos
Extensión JSONView: Permite abrir documentos JSON en el navegador Firefox.
Json y Android
Clase JSONObject
| JSONObject(String json) | Creates a new JSONObject with name/value mappings from the JSON string. |
| getInt(String name) | Returns the value mapped by name if it exists and is an int or can becoerced to an int, or throws otherwise. |
| getString(String name) | Returns the value mapped by name if it exists, coercing it if necessary, or throws if no such mapping exists. |
| getJSONObject(String name) | Returns the value mapped by name if it exists and is a JSONObject, or throws otherwise. |
| put(String name, int value) | Maps name to value, clobbering any existing name/value mapping with the same name. |
| toString() | Encodes this object as a compact JSON string. |
Clase JSONArray
| JSONArray(String json) | Creates a new JSONArray with values from the JSON string. |
| toString(int indentSpaces) | Encodes this array as a human readable JSON string for debugging |
| getJSONArray(String name) | Returns the value mapped by name if it exists and is a JSONArray or throws otherwise |
Parsing JSON in Android
Ejemplo: Lista de contactos
Crear una aplicación que lea una lista de contactos almacenada en un fichero en formato json (situado en la carpeta res/raw o en la tarjeta de memoria).
Cada contacto contendrá los campos: nombre, dirección, email y teléfono. En el teléfono se podrán guardar tres valores (casa, móvil y trabajo).

¿contactos.json?
añadir contactos.json a la carpeta res/raw
view Binding en build.gradle
buildFeatures {
viewBinding = true
}
acitvity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lista de contactos"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022" />
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="Gson"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.95"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="16dp"
android:text="Mostrar"
app:layout_constraintBottom_toTopOf="@+id/recyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.462"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="362dp"
android:layout_height="561dp"
android:layout_marginBottom="28dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.326"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
item_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<TextView
android:id="@+id/contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="name"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="#2196F3" />
<TextView
android:id="@+id/mobile_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
</LinearLayout>
Telefono.java
public class Telefono {
private String casa;
private String movil;
private String trabajo;
public String getCasa() {
return casa;
}
public void setCasa(String casa){
this.casa = casa;
}
public String getMovil() {
return movil;
}
public void setMovil(String movil) {
this.movil = movil;
}
public String getTrabajo() {
return trabajo;
}
public void setTrabajo(String trabajo) {
this.trabajo = trabajo;
}
}
Contacto.java
public class Contacto {
private String nombre;
private String direccion;
private String email;
private Telefono telefono;
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Telefono getTelefono() {
return telefono;
}
public void setTelefono(Telefono telefono) {
this.telefono = telefono;
}
public String toString() {
return nombre;
}
}
ContactosAdapter.java
// Create the basic adapter extending from RecyclerView.Adapter
// Note that we specify the custom ViewHolder which gives us access to our views
public class ContactosAdapter extends RecyclerView.Adapter<ContactosAdapter.ViewHolder> {
// Store a member variable for the contacts
private List<Contacto> mContactos;
// Pass in the contact array into the constructor
public ContactosAdapter(List<Contacto> contactos) {
mContactos = contactos;
}
// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
public class ViewHolder extends RecyclerView.ViewHolder{
// Your holder should contain a member variable
// for any view that will be set as you render a row
public TextView nameTextView;
public TextView mobileTextView;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public ViewHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
nameTextView = (TextView) itemView.findViewById(R.id.contact_name);
mobileTextView = (TextView) itemView.findViewById(R.id.mobile_phone);
}
}
// Usually involves inflating a layout from XML and returning the holder
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.item_contact, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
// Involves populating data into the item through holder
@Override
public void onBindViewHolder(ContactosAdapter.ViewHolder holder, int position) {
// Get the data model based on position
Contacto contact = mContactos.get(position);
// Set item views based on your views and data model
TextView textView1 = holder.nameTextView;
textView1.setText(contact.getNombre());
TextView textView2 = holder.mobileTextView;
textView2.setText(contact.getTelefono().getMovil());
}
// Returns the total count of items in the list
@Override
public int getItemCount() {
return mContactos.size();
}
public void actualizar(List<Contacto> data) {
this.mContactos = data;
notifyDataSetChanged();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int CONTACTOS = R.raw.contactos;
public static final int CONTACTS = R.raw.contacts;
private ActivityMainBinding binding;
ArrayList<Contacto> contactos = null;
ContactosAdapter adapter;
String contenido;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
binding.button.setOnClickListener(this);
// onClick(binding.button);
}
@Override
public void onClick(View v) {
if (v == binding.button) {
obtenerContactos();
if (contactos != null)
if (adapter != null) {
// adapter.notifyDataSetChanged();
// adapter.notifyItemRangeChanged(0, contactos.size());
adapter.actualizar(contactos);
} else
crearAdapter();
else
mostrarMensaje("Error al obtener los contactos");
}
}
private void crearAdapter() {
// Create adapter passing in the sample user data
adapter = new ContactosAdapter(contactos);
// Attach the adapter to the recyclerview to populate items
binding.recyclerView.setAdapter(adapter);
// Set layout manager to position the items
binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
public void obtenerContactos() {
// Initialize contacts
try {
if (!binding.switch1.isChecked()) {
// Analizar contactos
contenido = leerFicheroRaw(CONTACTOS);
contactos = Analisis.analizarContactos(contenido);
} else {
// usar Gson
}
} catch (JSONException | IOException e) {
//e.printStackTrace();
Log.e("Error: ", e.getMessage());
mostrarMensaje("Error: " + e.getMessage());
} catch ( JsonSyntaxException ex) {
Log.e("Error: ", ex.getMessage());
mostrarMensaje("Error: " + ex.getMessage());
}
}
public String leerFicheroRaw(int id) throws IOException {
StringBuilder cadena = new StringBuilder();
String linea = "";
InputStream in = getApplicationContext().getResources().openRawResource(id);
// Otra forma
// String filePath = "res/raw/fichero_raw";
// InputStream in = this.getClass().getClassLoader().getResourceAsStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((linea = br.readLine()) != null) {
cadena.append(linea + "\n");
}
in.close();
return cadena.toString();
}
private void mostrarMensaje(String texto) {
Toast.makeText(this, texto, Toast.LENGTH_SHORT).show();
}
}
Análisis del fichero json
utils/Analisis.java
public class Analisis {
public static ArrayList<Contacto> analizarContactos(String cadena) throws JSONException {
JSONArray jAcontactos;
JSONObject objeto, jOcontacto, jOtelefono;
Contacto contacto;
Telefono telefono;
ArrayList<Contacto> personas = new ArrayList<>();
// añadir contactos (en formato JSON) a personas
}
}

Deja una respuesta
Lo siento, debes estar conectado para publicar un comentario.