2016-01-18 249 views
0

即時通訊嘗試讓我的應用程序連接到其他API並從中獲取數據。迄今爲止,我一直拉取數據。但我不知道如何解析它。我相信那就是你接下來要做的事情。Android和Json解析

這裏是我的代碼片段,它能夠提供我的其餘API並獲取數據。我得到的錯誤是JSONArray不能被轉換爲JSONObject的

if (status == 200) { 
       InputStream is = conn.getInputStream(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
       String responseString; 
       StringBuilder sb = new StringBuilder(); 

       while ((responseString = reader.readLine()) != null) { 
        sb = sb.append(responseString); 
       } 
       String speciesListData = sb.toString(); 
       species= SpeciesJson.fromJson(speciesListData); 
       Log.d(Constants.TAG, "speciesJSON: " + species); 
       return true; 
      } 

這是我試圖解析它,它工作正常,直到這裏。她是該行是我嘗試分析它

species= SpeciesJson.fromJson(speciesListData); 

,這是多數民衆贊成它打破了笑

public class SpeciesJson { 
    private String scientific_name, name,description; 


    public SpeciesJson (JSONObject species) throws JSONException { 

     this.scientific_name=species.optString("scientific_name"); 
     this.name=species.optString("name"); 
     this.description=species.optString("description"); 

    } 
    public static ArrayList<SpeciesJson> fromJson(String photoData) throws JSONException { 
     ArrayList<SpeciesJson> speciesData = new ArrayList<>(); 
     JSONObject data = new JSONObject(photoData); 
     JSONObject photos = data.optJSONObject("name"); 
     JSONArray photoArray = photos.optJSONArray("name"); 

     for (int i = 0; i < photoArray.length(); i++) { 
      JSONObject photo = (JSONObject) photoArray.get(i); 
      SpeciesJson currentPhoto = new SpeciesJson(photo); 
      speciesData.add(currentPhoto); 
     } 
     return speciesData; 
    } 

因此,當我使用的解析方法,我做運行它,它不無法正常工作。

興田JSON數據的樣品低於,我嘗試以顯示scientific_name和名稱在視圖

{ 
     "id": 1, 
     "scientific_name": "Platanus racemosa", 
     "name": "California Sycamore", 
     "description": "typically in river areas, but planted all throughout L.A", 
     "type": 1 
    }, 
    { 
     "id": 2, 
     "scientific_name": "Pyrus kawakamii", 
     "name": "Ornamental Pear", 
     "description": "native to Asia, commonly planted in L.A", 
     "type": 1 
    }, 
    { 
     "id": 3, 
     "scientific_name": "Liquidambar styraciflua", 
     "name": "American Sweetgum", 
     "description": "native to SE U.S, planted all around L.A", 
     "type": 1 
    }, 
    { 
     "id": 4, 
     "scientific_name": "Setophaga coronata", 
     "name": "Yellow-rumped Warbler", 
     "description": "native bird, spends the winter in L.A before migrating north during the summer to breed", 
     "type": 2 
    }, 
    { 
     "id": 5, 
     "scientific_name": "Calypte anna", 
     "name": "Anna's Hummingbird", 
     "description": "native bird, does not migrate. Spends the year in L.A", 
     "type": 2 
    }, 
    { 
     "id": 6, 
     "scientific_name": "Regulus calendula", 
     "name": "Ruby-crowned Kinglet", 
     "description": "native bird, spends the winter in L.A before migrating north during the summer to breed", 
     "type": 2 
    } 
] 
+0

請發佈與解析相關的錯誤,如果可能的話發佈Json數據以及 –

+0

您是否有一些JSON數據示例? –

+0

我加了一個json的樣本 –

回答

1

我親愛的朋友使用網上搜尋GSON圖書館就是這樣。

爲了您的幫助,我簡化了這一點。

使這個類SpeciesJson.java

public class SpeciesJson { 

    private String scientific_name; 
    private String name; 
    private String description; 

public SpeciesJson() { 
} 

public SpeciesJson(String scientific_name,String name,String description) { 
    this.scientific_name = scientific_name; 
    this.name = name; 
    this.description = description; 
} 


//And getter,setters 
} 

如果SpeciesJson是簡單的物體,然後使用這個

Gson gson = new Gson(); 
SpeciesJson species = gson.fromJson(responseString,SpeciesJson.class); 

如果SpeciesJson然後一個ArrayList所以用這個(它看起來像你的情況檢查這是你的Json響應包含多種Specsonson對象)

Gson gson = new Gson(); 
ArrayList<SpeciesJson> species = new ArrayList<>(); 
SpeciesJson[] speciesarray = (SpeciesJson[]) gson.fromJson(responseString,SpeciesJson[].class); 
Collections.addAll(species, speciesarray); 

,如果你想了解GSON圖書館更多的東西檢查此鏈接 https://guides.codepath.com/android/Leveraging-the-Gson-Library

0

那麼你可以使用GSON解析數據和截擊來獲取數據。

//Create volley request 
      String url = String.format("SOME_URL", arrayOfObject); 

     RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue(); 
     StringRequest request = new StringRequest(url, new Response.Listener<String>() { 

      @Override 
      public void onResponse(String response) { 
       // we got the response, now our job is to handle it 
       try {       
        ArrayList<SpeciesJson> speciesData = getDataFromJson(stream); 

       } catch (RemoteException | OperationApplicationException e) { 
        e.printStackTrace(); 
       } 
      } 
     }, new Response.ErrorListener() { 

      @Override 
      public void onErrorResponse(VolleyError error) { 
       //something happened, treat the error. 
       Log.e("Error", error.toString()); 
      } 
     }); 

     queue.add(request); 

//If your JSON data is an Array 
    private static List<SpeciesJson> getDataFromJson(String json) { 
     Gson gson = new GsonBuilder().create(); 
     List<SpeciesJson> result = new ArrayList<>(); 
     try { 
      JSONObject posts=new JSONObject(json); 
      JSONArray dataArray=posts.getJSONArray("data"); 
      for(int n = 0; n < dataArray.length(); n++) 
      { 
       JSONObject object = dataArray.getJSONObject(n); 
       result.add(gson.fromJson(object.toString(), SpeciesJson.class)); 
      } 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return result; 
    } 

抽射服務

public class VolleyService { 

    private static VolleyService instance; 
    private RequestQueue requestQueue; 
    private ImageLoader imageLoader; 

    private VolleyService(Context context) { 
     requestQueue = Volley.newRequestQueue(context); 

     imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() { 
      private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20); 

      @Override 
      public Bitmap getBitmap(String url) { 
       return cache.get(url); 
      } 

      @Override 
      public void putBitmap(String url, Bitmap bitmap) { 
       cache.put(url,bitmap); 
      } 
     }); 
    } 

    public static VolleyService getInstance(Context context) { 
     if (instance == null) { 
      instance = new VolleyService(context); 
     } 
     return instance; 
    } 

    public RequestQueue getRequestQueue() { 
     return requestQueue; 
    } 

    public ImageLoader getImageLoader() { 
     return imageLoader; 
    } 
} 

或者您可以使用改造庫來解析它爲您:

http://www.vogella.com/tutorials/Retrofit/article.html https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit

+0

反正有沒有這些外面的東西呢?我搞砸了我的代碼試圖導入Gson哈哈。 –