JsonReader.setLenient (true)를 사용하여 1 행 1 열 경로 $에서 잘못된 형식의 JSON을 허용하십시오.
이 오류는 무엇입니까? 이 문제를 어떻게 해결할 수 있습니까? 내 앱이 실행 중이지만 데이터를로드 할 수 없습니다. 그리고 이것은 내 오류입니다 .JsonReader.setLenient (true)를 사용하여 줄 1 열 1 경로에서 잘못된 JSON을 수락하십시오 $
이것은 내 조각입니다.
public class news extends Fragment {
private RecyclerView recyclerView;
private ArrayList<Deatails> data;
private DataAdapter adapter;
private View myFragmentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.news, container, false);
initViews();
return myFragmentView;
}
private void initViews() {
recyclerView = (RecyclerView) myFragmentView.findViewById(R.id.card_recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
data = new ArrayList<Deatails>();
adapter = new DataAdapter(getActivity(), data);
recyclerView.setAdapter(adapter);
new Thread()
{
public void run()
{
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
loadJSON();
}
});
}
}
.start();
}
private void loadJSON() {
if (isNetworkConnected()){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.connectTimeout(15, TimeUnit.SECONDS)
.build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.memaraneha.ir/")
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.show();
call.enqueue(new Callback<JSONResponse>() {
@Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
progressDialog.dismiss();
JSONResponse jsonResponse = response.body();
data.addAll(Arrays.asList(jsonResponse.getAndroid()));
adapter.notifyDataSetChanged();
}
@Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
progressDialog.dismiss();
Log.d("Error", t.getMessage());
}
});
}
else {
Toast.makeText(getActivity().getApplicationContext(), "Internet is disconnected", Toast.LENGTH_LONG).show();}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
}
RequestInterface :
public interface RequestInterface {
@GET("Erfan/news.php")
Call<JSONResponse> getJSON();
}
최신 정보
항상이 오류는 json에 관한 것이 아니라 잘못된 요청으로 인해 발생할 수 있습니다. 응답을 받으면 먼저 우편 배달부에서 요청을 확인한 다음 json 응답을 모델과 비교하십시오.이 오류는 잘못된 요청에서 비롯된 것입니다. 또한 응답이 josn이 아닐 때 발생할 수 있습니다 (어떤 경우에는 응답이 html 일 수 있음)
이것은 잘 알려진 문제 이며이 답변을 기반으로 다음을 추가 할 수 있습니다 setLenient
.
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
Now, if you add this to your retrofit, it gives you another error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
This is another well-known error you can find answer here (this error means that your server response is not well-formatted); So change server response to return something:
{
android:[
{ ver:"1.5", name:"Cupcace", api:"Api Level 3" }
...
]
}
For better comprehension, compare your response with Github api.
Suggestion: to find out what's going on to your request/response
add HttpLoggingInterceptor
in your retrofit.
Based on this answer your ServiceHelper would be:
private ServiceHelper() {
httpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.interceptors().add(interceptor);
Retrofit retrofit = createAdapter().build();
service = retrofit.create(IService.class);
}
Also don't forget to add:
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
Also this issue occurres when the response contenttype is not application/json
. In my case response contenttype was text/html
and i faced this problem. I changed it to application/json
then it worked.
I had same issue along with https://stackoverflow.com/a/57245058/8968137 and both solved after fixing the google-services.json
There was an error in understanding of return Type Just add Header and it will solve your problem
@Headers("Content-Type: application/json")
In my case ; what solved my issue was.....
You may had json like this, the keys without " double quotations....
{ name: "test", phone: "2324234" }
So try any online Json Validator to make sure you have right syntax...
I have faced this problem and I made research and didn't get anything, so I was trying and finally, I knew the cause of this problem. the problem on the API, make sure you have a good variable name I used $start_date and it caused the problem, so I try $startdate and it works!
as well make sure you send all parameter that declare on API, for example, $startdate = $_POST['startdate']; $enddate = $_POST['enddate'];
you have to pass this two variable from the retrofit.
as well if you use date on SQL statement, try to put it inside '' like '2017-07-24'
I hope it helps you.
if your JSON formats are okay check your database queries. Try changing them and retry
이 문제는 갑자기 나에게 발생하기 시작했기 때문에 다른 이유가있을 수 있다고 확신했습니다. 깊이 파고 http
들 때 .NET 대신 Retrofit의 BaseUrl에서 사용한 간단한 문제 였습니다 https
. 그래서 그것을 변경 https
하여 문제 를 해결했습니다.
또한 인터페이스 메서드의 반환 유형에 오류가 있는지 확인할 가치가 있습니다. 다음과 같은 의도하지 않은 반환 유형을 사용하여이 문제를 재현 할 수 있습니다.Call<Call<ResponseBody>>
'developer tip' 카테고리의 다른 글
pandas 데이터 프레임을 여러 열로 필터링하는 방법 (0) | 2020.10.12 |
---|---|
Docker에 최소 플라스크 앱 배포-서버 연결 문제 (0) | 2020.10.12 |
ts ES5 / ES3의 비동기 함수 또는 메서드에는 'Promise'생성자가 필요합니다. (0) | 2020.10.12 |
print 문을 사용할 때 특수 문자 표시 (0) | 2020.10.12 |
MSYS에서 폴더 찾아보기 (0) | 2020.10.12 |