JSON
qué es JSON
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" } ] } |
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 |
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 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>
MainActivity.java
public class MainActivity extends AppCompatActivity { private ActivityMainBinding binding; ArrayList<Contacto> contactos; 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); } }
leer el fichero raw
public String leerFicheroRaw() throws IOException { StringBuilder cadena = new StringBuilder(); String linea = ""; InputStream in = getApplicationContext().getResources().openRawResource(R.raw.contactos); // 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(); }
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; } }
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; } }
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> mContacts; // Pass in the contact array into the constructor public ContactosAdapter(List<Contacto> contacts) { mContacts = contacts; } // 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 = mContacts.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 mContacts.size(); } }
Análisis del fichero json
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 JSON) a personas } }
crearAdapter()
private void crearAdapter() { // Crear el adapter }
obtenerContactos()
public void obtenerContactos() { // Inicializar contactos }
Deja una respuesta
Lo siento, debes estar conectado para publicar un comentario.