2016-07-25 4 views
0

JSON 및 Retrofit 라이브러리를 사용하여 Recyclerview에 CardViews로 피드를 표시하려고합니다. 나는이 문제에 대해 4 시간 1 시간 동안 Google 검색 중이지만 아직 성공하지 못했습니다.JSON을 개조하여 구문 분석하려고 할 때 IllegalStateException이 발생했습니다.

D/Error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ D/Error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $


JSON 예 PHP API의 :

[{"id":"143","uploadID":"36","type":"excellent","userID":"58","username":"doitlikeaves","date":"31 May","timestamp":"2016-05-31 22:37:50","title":"PH Zusammenfassung #2","subject":"Physik"},{"id":"142","uploadID":"36","type":"presentation","userID":"58","username":"doitlikeaves","date":"31 May","timestamp":"2016-05-31 21:57:21","title":"PH Zusammenfassung #2","subject":"Physik"},{"id":"141","uploadID":"61","type":"document","userID":"56","username":"maja","date":"31 May","timestamp":"2016-05-31 14:29:00","title":" Rev.","subject":"Geschichte"}] 


상관없이 나는 다음과 같은 오류가 무엇을하려고

0

안드로이드 파일 :

FeedElement.js :

import com.google.gson.annotations.Expose; 
import com.google.gson.annotations.SerializedName; 

public class FeedElement { 

    @SerializedName("id") 
    @Expose 
    private String id; 
    @SerializedName("uploadID") 
    @Expose 
    private String uploadID; 
    @SerializedName("type") 
    @Expose 
    private String type; 
    @SerializedName("userID") 
    @Expose 
    private String userID; 
    @SerializedName("username") 
    @Expose 
    private String username; 
    @SerializedName("date") 
    @Expose 
    private String date; 
    @SerializedName("timestamp") 
    @Expose 
    private String timestamp; 
    @SerializedName("title") 
    @Expose 
    private String title; 
    @SerializedName("subject") 
    @Expose 
    private String subject; 

    /** 
    * 
    * @return 
    * The id 
    */ 
    public String getId() { 
     return id; 
    } 

    /** 
    * 
    * @param id 
    * The id 
    */ 
    public void setId(String id) { 
     this.id = id; 
    } 

    /** 
    * 
    * @return 
    * The uploadID 
    */ 
    public String getUploadID() { 
     return uploadID; 
    } 

    /** 
    * 
    * @param uploadID 
    * The uploadID 
    */ 
    public void setUploadID(String uploadID) { 
     this.uploadID = uploadID; 
    } 

    /** 
    * 
    * @return 
    * The type 
    */ 
    public String getType() { 
     return type; 
    } 

    /** 
    * 
    * @param type 
    * The type 
    */ 
    public void setType(String type) { 
     this.type = type; 
    } 

    /** 
    * 
    * @return 
    * The userID 
    */ 
    public String getUserID() { 
     return userID; 
    } 

    /** 
    * 
    * @param userID 
    * The userID 
    */ 
    public void setUserID(String userID) { 
     this.userID = userID; 
    } 

    /** 
    * 
    * @return 
    * The username 
    */ 
    public String getUsername() { 
     return username; 
    } 

    /** 
    * 
    * @param username 
    * The username 
    */ 
    public void setUsername(String username) { 
     this.username = username; 
    } 

    /** 
    * 
    * @return 
    * The date 
    */ 
    public String getDate() { 
     return date; 
    } 

    /** 
    * 
    * @param date 
    * The date 
    */ 
    public void setDate(String date) { 
     this.date = date; 
    } 

    /** 
    * 
    * @return 
    * The timestamp 
    */ 
    public String getTimestamp() { 
     return timestamp; 
    } 

    /** 
    * 
    * @param timestamp 
    * The timestamp 
    */ 
    public void setTimestamp(String timestamp) { 
     this.timestamp = timestamp; 
    } 

    /** 
    * 
    * @return 
    * The title 
    */ 
    public String getTitle() { 
     return title; 
    } 

    /** 
    * 
    * @param title 
    * The title 
    */ 
    public void setTitle(String title) { 
     this.title = title; 
    } 

    /** 
    * 
    * @return 
    * The subject 
    */ 
    public String getSubject() { 
     return subject; 
    } 

    /** 
    * 
    * @param subject 
    * The subject 
    */ 
    public void setSubject(String subject) { 
     this.subject = subject; 
    } 

} 

JSONResponseFeed.js :

import java.util.ArrayList; 
public class JSONResponseFeed { 
    private ArrayList<FeedElement> feeds; 

    /** 
    * @return The feeds 
    */ 
    public ArrayList<FeedElement> getFeed() { 
     return feeds; 
    } 
} 

RequestInterfaceFeed.js :

,938,748,129,733,995,863,210

DataAdapterFeed.js :

import android.support.v7.widget.RecyclerView; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.TextView; 

import java.util.List; 

public class DataAdapterFeed extends RecyclerView.Adapter<DataAdapterFeed.ViewHolder> { 
    private List<FeedElement> feed; 

public DataAdapterFeed(List<FeedElement> feed) { 
    this.feed = feed; 
} 

@Override 
public DataAdapterFeed.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { 
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false); 
    return new ViewHolder(view); 
} 

@Override 
public void onBindViewHolder(DataAdapterFeed.ViewHolder viewHolder, int i) { 

    viewHolder.tv_name.setText(feed.get(i).getUsername()); 
} 

@Override 
public int getItemCount() { 
    return feed.size(); 
} 

public class ViewHolder extends RecyclerView.ViewHolder{ 
    private TextView tv_name; 
    public ViewHolder(View view) { 
     super(view); 

     tv_name = (TextView)view.findViewById(R.id.username); 

     } 
    } 
} 

기능 MainActivity.js에서 :

private void loadJSON(){ 
    final String url = "https://mydomainiscorrect.justreplacedithere/api/v1/"; 
    Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl(url) 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build(); 
    final RequestInterfaceFeed request = retrofit.create(RequestInterfaceFeed.class); 
    Call<JSONResponseFeed> call = request.getJSON(apiKey); 
    call.enqueue(new Callback<JSONResponseFeed>() { 
     @Override 
     public void onResponse(Call<JSONResponseFeed> call, retrofit2.Response<JSONResponseFeed> response) { 
      List<FeedElement> data = response.body().getFeed(); 
      adapter = new DataAdapterFeed(data); 
      recyclerView.setAdapter(adapter); 
     } 

     @Override 
     public void onFailure(Call<JSONResponseFeed> call, Throwable t) { 
      Log.d("Error", t.getMessage()); 
     } 
    }); 
} 

private void initViews(){ 
    recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view); 
    recyclerView.setHasFixedSize(true); 
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); 
    recyclerView.setLayoutManager(layoutManager); 
    loadJSON(); 
} 

만약 필요 - cardView.xml :

<android.support.v7.widget.CardView 
xmlns:card_view="http://schemas.android.com/apk/res-auto" 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:layout_marginTop="5dp" 
android:layout_marginLeft="5dp" 
android:layout_marginRight="5dp" 
card_view:cardCornerRadius="5dp"> 
<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_margin="10dp" 
    android:orientation="vertical"> 
    <TextView 
     android:id="@+id/username" 
     android:layout_marginTop="10dp" 
     android:layout_marginBottom="10dp" 
     android:textSize="18sp" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textStyle="bold" /> 
</LinearLayout> 


MainActivity RecyclerView의 XML :

<android.support.v7.widget.RecyclerView 
     android:id="@+id/card_recycler_view" 
     android:scrollbars="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"/> 


내가 STIL 자바와 안드로이드 프로그래밍에 아주 새로운 해요, PHP는 꽤 잘 알고 있지만, 자바는 정말 제공 나 때때로 두통.

나를 도와 주심에 감사드립니다. 정말 고맙습니다!

+1

확인 당신을 도울 수도 유래 스레드. http://stackoverflow.com/questions/9598707/gson-throwing-expected-begin-object-but-was-begin-array – lsiva

+0

@Isiva는 이미 그 스레드를 보았지만 더 이상 궁금해하게 만들었습니다. 대답이 무엇을 말하고, 내 코드가 실제로 잘못되었는지 알지 못한다. 내 앱이 충돌하지 않기 때문이다./ –

+0

내 대답 확인 http://stackoverflow.com/questions/38418556/expected-begin- gss-and-retrofit과 함께 시작했지만 배열이 시작된 개체/38418739 # 38418739 – USKMobility

답변

1

JSONResponseFeed이 필요하지 않습니다 :

당신은 당신의 코드는 당신이 JSON의 필수있어 생각하고 작동하려는 경우처럼 보인다. 업데이트

public interface RequestInterfaceFeed { 
    @GET("getFeed") 
    Call<List<FeedElement>> getJSON(@Query("key") String apiKey); 
} 

을 RequestInterfaceFeed 그리고 업데이트 loadJSON 방법

private void loadJSON(){ 
    final String url = "https://mydomainiscorrect.justreplacedithere/api/v1/"; 
    Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl(url) 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build(); 
    final RequestInterfaceFeed request = retrofit.create(RequestInterfaceFeed.class); 
    Call<List<FeedElement>> call = request.getJSON(apiKey); 
    call.enqueue(new Callback<List<FeedElement>>() { 
     @Override 
     public void onResponse(Call<List<FeedElement>> call, retrofit2.Response<List<FeedElement>> response) { 
      List<FeedElement> data = response.body(); 
      adapter = new DataAdapterFeed(data); 
      recyclerView.setAdapter(adapter); 
     } 

     @Override 
     public void onFailure(Call<List<FeedElement>> call, Throwable t) { 
      Log.d("Error", t.getMessage()); 
     } 
    }); 
} 
+0

고맙습니다. 정답입니다! –

0

난 당신과 비슷한 일을)하지만

public class ListClubs extends LinkedList<Club> { 
} 

내 서비스처럼 보이는 상속에 의해 요소의 목록을 가지고 :

public interface ClubService { 

    @GET("/clubs") 
    Call<ListClubs> getClubs(); 

    @GET("/clubs/{id}") 
    Call<ClubDetail> getClub(@Path("id") String id); 

} 

그리고이 잘 작동합니다.

{feeds:[{"id":"143","uploadID":"36","type":"excellent","userID":"58","username":"doitlikeaves","date":"31 May","timestamp":"2016-05-31 22:37:50","title":"PH Zusammenfassung #2","subject":"Physik"},{"id":"142","uploadID":"36","type":"presentation","userID":"58","username":"doitlikeaves","date":"31 May","timestamp":"2016-05-31 21:57:21","title":"PH Zusammenfassung #2","subject":"Physik"},{"id":"141","uploadID":"61","type":"document","userID":"56","username":"maja","date":"31 May","timestamp":"2016-05-31 14:29:00","title":" Rev.","subject":"Geschichte"}]} 
+0

고맙습니다. json을 제공 한 것처럼 고맙습니다. –

+0

"잘못된 JSON" 오류 :/ –

관련 문제