2016-02-11 2 views
0

Я работал над анализом объектов JSON, возвращаемых Facebook. Одна из библиотек, на которые я опиралась, - это Gson. Цель состояла в том, чтобы заполнить ListView, созданный в приложении Android, с фотографиями пользователя, найденными в его профиле, под фотографиями вашего раздела. Таким образом, я использовал следующую команду:Анализ объекта Facebook Json с использованием библиотеки Gson

GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(), "/" + profile.getId() +  "/photos", null, 
        HttpMethod.GET, new GraphRequest.Callback() { 

      @Override 
      public void onCompleted(GraphResponse response) { 
       jsonObject = response.getJSONObject(); 
       Log.d("JSON", "response is returned"); 
       communicator.openFragment(jsonObject); 
      } 
     } 
     ); 
     // This is how to use the fields 
     Bundle parameters = new Bundle(); 
     parameters.putString("fields", "images"); 
     request.setParameters(parameters); 
     request.executeAsync(); 

Объект JSON был отправлен в Основной вид деятельности приложения собирался отправить один и тот же объект JSON в другой фрагмент. Моя проблема связана с разбором объекта JSON.

Я использовал 2 класса для этой цели: один из которых является класс Response Вот код:

public class Response { 

private PagingEntity paging; 

private List<DataEntity> data; 

public Response() { 

} 

public void setPaging(PagingEntity paging) { 
    this.paging = paging; 
} 

public void setData(List<DataEntity> data) { 
    this.data = data; 
} 

public PagingEntity getPaging() { 
    return paging; 
} 

public List<DataEntity> getData() { 
    return data; 
} 

public static class PagingEntity { 

    private CursorsEntity cursors; 
    private String next; 

    public void setCursors(CursorsEntity cursors) { 
     this.cursors = cursors; 
    } 

    public void setNext(String next) { 
     this.next = next; 
    } 

    public CursorsEntity getCursors() { 
     return cursors; 
    } 

    public String getNext() { 
     return next; 
    } 

    public static class CursorsEntity { 
     private String after; 
     private String before; 

     public void setAfter(String after) { 
      this.after = after; 
     } 

     public void setBefore(String before) { 
      this.before = before; 
     } 

     public String getAfter() { 
      return after; 
     } 

     public String getBefore() { 
      return before; 
     } 
    } 
} 

public static class DataEntity { 
    private String id; 

    private List<ImagesEntity> images; 

    public void setId(String id) { 
     this.id = id; 
    } 

    public void setImages(List<ImagesEntity> images) { 
     this.images = images; 
    } 

    public String getId() { 
     return id; 
    } 

    public List<ImagesEntity> getImages() { 
     return images; 
    } 

    public static class ImagesEntity { 
     private String source; 
     private int width; 
     private int height; 

     public void setSource(String source) { 
      this.source = source; 
     } 

     public void setWidth(int width) { 
      this.width = width; 
     } 

     public void setHeight(int height) { 
      this.height = height; 
     } 

     public String getSource() { 
      return source; 
     } 

     public int getWidth() { 
      return width; 
     } 

     public int getHeight() { 
      return height; 
     } 
    } 
} 
} 

CustomAdapter, который использует этот класс выглядит следующим образом:

public class CustomAdapter extends BaseAdapter{ 
private List<Response.DataEntity> dataEntityList; 
private Context context; 

public CustomAdapter(Context context, List<Response.DataEntity> dataEntityList) { 
    this.context = context; 
    this.dataEntityList = dataEntityList; 
} 

@Override 
public int getCount() { 
    return dataEntityList.size(); 
} 

@Override 
public Object getItem(int position) { 
    return dataEntityList.get(position); 
} 

@Override 
public long getItemId(int position) { 
    return 0; 
} 

public Object getImage(int imageSet) { 
    return dataEntityList.get(imageSet).getImages() 
      .get(dataEntityList.get(imageSet).getImages().size() - 1); 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View rowView = inflater.inflate(R.layout.each_item_list, parent, false); 

    ImageView thumbnail = (ImageView) rowView.findViewById(R.id.thumbnail); 
    TextView height = (TextView) rowView.findViewById(R.id.height); 
    TextView width = (TextView) rowView.findViewById(R.id.width); 

    Response.DataEntity.ImagesEntity item = (Response.DataEntity.ImagesEntity) getImage(position); 
    String imageURL = item.getSource(); 

    Picasso.with(context).load(imageURL).into(thumbnail); 
    height.setText(item.getHeight() + ""); 
    width.setText(item.getWidth() + ""); 

    return rowView; 
} 
} 

Therfore , Я смог разобрать объект JSON и извлечь URL-адреса изображений, но я не знаю, как получить оставшиеся изображения из-за функций разбиения на страницы в возвращаемых объектах JSON по facebook. код для синтаксического анализа выглядит следующим образом: (Это было добавлено в onCreateView в фрагменте)

gson = new Gson(); 
    String jsonFetched = jsonObject.toString(); 
    String jsonToPass = jsonFetched.replace("\\/", "/"); 
    response = gson.fromJson(jsonToPass, Response.class); 
    adapter = new CustomAdapter(getActivity().getBaseContext(), response.getData()); 
    listView.setAdapter(adapter); 
    return view; 

Пожалуйста, помогите мне, как разобрать остальную часть объекта JSON, то есть, автоматически происходит через «следующий» тег в объекте JSON, чтобы получить следующий JSON объект и разобрать его и так далее

Любые очень оцененным .... СПАСИБО

ответ

0

чтобы получить остальную часть изображений, вот мой новый код:

final GraphRequest.Callback graphCallback = new GraphRequest.Callback(){ 
     @Override 
     public void onCompleted(GraphResponse response) { 
       Bundle parameters = new Bundle(); 
       parameters.putString("fields", "images"); 
       parameters.putString("limit", "50"); 
       jsonObject = response.getJSONObject(); 
       GraphRequest newRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT); 
       newRequest.setGraphPath("/" + profile.getId() + "/photos"); 
       newRequest.setCallback(this); 
       newRequest.setParameters(parameters); 
       newRequest.executeAsync(); 
     } 
    }; 

Обратите внимание, что информация, содержащаяся на разработчиков facebook недостаточно https://developers.facebook.com/docs/reference/android/current/class/GraphResponse/ Поэтому я должен добавить GraphPath, CallBack и связки параметров.

Наконец, этот объект GraphRequest.Call должен быть добавлен объект запроса GraphRequest следующим образом:

final GraphRequest request = new GraphRequest(
       AccessToken.getCurrentAccessToken(), "/" + profile.getId() + "/photos", null, 
       HttpMethod.GET, graphCallback 
     );