2015-10-05 17 views
21

Il nostro team decide di utilizzare Retrofit 2.0 e sto facendo qualche ricerca iniziale su questa libreria. Come indicato nel titolo, voglio analizzare alcuni oggetti JSON nidificati tramite Retrofit 2.0 nella nostra app per Android.In che modo Retrofit 2.0 può analizzare l'oggetto JSON annidato?

Ad esempio, here è un oggetto JSON nidificata con il formato:

{ 
     "title": "Recent Uploads tagged android", 
     "link": "https://www.flickr.com/photos/tags/android/", 
     "description": "", 
     "modified": "2015-10-05T05:30:01Z", 
     "generator": "https://www.flickr.com/", 
     "items": [ 
     { 
      "title": ... 
      "link": ... 
      "media": {"m":"This is the value I want to get:)"} 
      "description": ... 
      "published": ... 
      "author": ... 
      "author_id": ... 
      "tags": ... 
     }, 
     {...}, 
     ... 
     ] 
} 

Mi interessa gli oggetti JSON all'interno items matrice. Ho notato che ci sono some posts sull'analisi degli oggetti JSON nidificati tramite Retrofit 1.X, ma le ultime API di Retrofit 2.0 sono cambiate molto, il che confonde quando le si adatta alle nuove API.

Due possibili soluzioni vengono in mente:

  1. scrivere la mia propria fabbrica convertitore JSON che si estende Converter.Factory.
  2. Restituisce la risposta non elaborata in un tipo String e la analizza da solo. Ma non è facile ottenere la risposta grezza da Retrofit 2.0 secondo la mia ricerca iniziale. Retrofit 2.0 sembra insistere nel convertire la risposta a qualcosa prima di passarmelo e Retrofit non fornisce il proprio StringConverter. (Potrei sbagliarmi ~)

Aggiornamento: Possiamo effettivamente ottenere la risposta grezzo impostando JSONElement come POJO per l'interfaccia API HTTP e utilizzare GSONConverter fornito dal retrofit come convertitore.

Sarebbe bello se qualcuno potesse condividere alcune idee su questo problema.

Grazie :)

+1

Cosa wil essere in elementi array? Puoi pubblicare anche quella parte? –

+1

@PankajKumar Aggiornato :) – hackjutsu

+1

Ho aggiunto una risposta simile al tuo JSON. Provalo. –

risposta

21

Assumendo che il completo JSON sembra

{ 
    "title": "Recent Uploads tagged android", 
    "link": "https://www.flickr.com/photos/tags/android/", 
    "description": "", 
    "modified": "2015-10-05T05:30:01Z", 
    "generator": "https://www.flickr.com/", 
    "items": [ 
    { 
     "member1": "memeber value", 
     "member2": "member value" 
    }, 
    { 
     "member1": "memeber value", 
     "member2": "member value" 
    } 
    ] 
} 

Quindi classi Pojo sarebbe

public class MainPojo { 
    private String title; 
    private String description; 
    private String link; 
    private String generator; 
    private String modified; 
    private ArrayList<Items> items; 

    // Getters setters 
} 

public class Items { 
    private String member2; 
    private String member1; 

    // Getters setters 
} 

Nota: Si tratta di una soluzione analoga per la tua JSON. I membri di Items.java possono essere modificati se JSON ha altre chiavi.


Aggiornamento per Pojo come nuovo JSON

public class Items { 
    private String tags; 
    private String author; 
    private String title; 
    private String description; 
    private String link; 
    private String author_id; 
    private String published; 
    private Media media; 

    // Getters and Setters 
} 

public class Media { 
    private String m; 
    // Getters and Setters 
} 
+1

@IgorGanapolsky Vedi la sezione aggiornata. Quello era un codice di esempio. –

+2

sta funzionando per ottenere richiesta, in caso di richiesta post sto ottenendo oggetto interno come null. Puoi spiegarci? – Spartan

+0

@Spartan Non ti ho preso. Meglio se chiedi una nuova domanda con il JSON in cui stai affrontando un problema. Non c'è alcuna relazione con la richiesta GET/POST con questa risposta. –

4

Usa GSON facile analisi per i vostri modelli https://github.com/google/gson Metodi

il mio aiuto:

public String toJson(Object object) { 
    return gson.toJson(object); 
} 

public <T> T fromJson(String json, Class<T> classOfT) { 
    return gson.fromJson(json, classOfT); 
} 

public <T> T fromJson(JsonElement jsonElement, Class<T> classOfT) { 
    return gson.fromJson(jsonElement, classOfT); 
} 
+0

Grazie :) Puoi condividere un po 'di luce su come scrivere l'interfaccia di Retrofit? Cosa dovrei inserire per il tipo generico 'T' per' Chiama httpApimethod (...) 'nell'API HTTP? Devo definire una classe con il campo 'items'? – hackjutsu

+0

@Hackjustu, il tipo generico 'T' sarà la tua classe pojo per' risposta json'. – Tauqir

+0

Quindi, dovrei definire una classe Java 'ItemsHolder' che contiene un' Elenco elementi'. Quindi posso ottenere le istanze di 'Item' dal campo' items' di 'ItemsHolder'. Mi manca qualcosa? Grazie :) – hackjutsu

0

hai provato al volo? ... preferisco il retrofit ora che è un prodotto google. Ho un esempio funzionante e se non ti dispiace posso mostrarti. http://www.androidhive.info/2014/09/android-json-parsing-using-volley/

+1

Grazie per il suggerimento :) In realtà, il nostro team decide di utilizzare Retrofit 2.0 e sto facendo alcune ricerche iniziali su questa libreria. – hackjutsu

+2

In che modo la pallavolo aiuta ad analizzare oggetti JSON? –

5

seguito il codice aiuterà a ottenere l'oggetto nidificato JSON e la matrice

ad esempio: json

{ 
    "similar_product":[ 
     { ..... 
} 
    ], 
    "options":{ 
     "Blouse Length":[ 
      { "value_id":"696556", 
       } 

prima abbiamo bisogno di creare la classe del modello, i nomi degli oggetti della classe del modello sono gli stessi nell'articolo json che possiamo usare @SerializedName("for exact json name")

public class Product { 

     public Options options; 

    public void setOptions(Options options) { 
     this.options = options; 
    } 

    public Options getOptions() { 
     return options; 
    } 


    // length... 

    public class Options 
    { 
     @SerializedName("Blouse Length") 
     private ArrayList<BlouseLength> blouseLengths; 


     public void setBlouseLengths(ArrayList<BlouseLength> blouseLengths) { 
      this.blouseLengths = blouseLengths; 
     } 

     public ArrayList<BlouseLength> getBlouseLengths() { 
      return blouseLengths; 
     } 
    } 



    public class BlouseLength { 
     String value_id; 
     public void setValue_id(String value_id) { 
      this.value_id = value_id; 
     } 



     public String getValue_id() { 
      return value_id; 
     } 
    } 

} 

creare Interfaccia per retrofit per ottenere oggetto JSON in url

// don't need to put values of id in retrofit 

ex:: "/api-mobile_.php?method=getProductById&pid=" 

basta passare parametro url nella query è recuperare automaticamente l'URL

ad esempio:

public interface Retrofit_Api { 

    @FormUrlEncoded 

    @GET("/api-mobile_.php?method=getProductById") 
    Call<Product> responseproduct(@Query("pid") String pid); 


} 

In la tua classe principale

 String pid=editid.getText().toString(); 


     final Retrofit adapter = new Retrofit.Builder() 
       .baseUrl(Product_url) 
       .addConverterFactory(GsonConverterFactory.create()) 
       .build(); 

     //Creating an object of our api interface 
     Retrofit_Api api = adapter.create(Retrofit_Api.class); 


     Call<Product> call = api.responseproduct(pid); 


     call.enqueue(new Callback<Product>() { 
      @Override 
      public void onResponse(Call<Product> call, Response<Product> response) { 


       ArrayList<Product.BlouseLength> p= new ArrayList(response.body().getOptions().getBlouseLengths()); 

Editadapter editadapter=new Editadapter(MainActivity.this,p); 

       recyclerView.setAdapter(editadapter); 


      } 

      @Override 
      public void onFailure(Call<Product> call, Throwable t) { 


       Log.d("Error", t.getMessage()); 
      } 
     }); 



    } 
0

Salam. Ho dimenticato di aggiungere le annotazioni @SerializedName e @Expose per gli oggetti di classe interna e dopo aver aggiunto queste annotazioni un problema risolto. Ti piace questa:

JSON:

{"Id": 1,} 

e membri della classe:

@SerializedName("Id") 
@Expose 
private int id;