gsonconverterfactory ejemplo android json gson retrofit

android - ejemplo - retrofit gson converter



Use JsonReader.setLenient(true) para aceptar JSON con formato incorrecto en la ruta de la columna 1 de la lĂ­nea 1 $ (8)

¿Qué es este error? ¿Cómo puedo arreglar esto? Mi aplicación se está ejecutando pero no puede cargar datos. Y este es mi error: use JsonReader.setLenient (true) para aceptar JSON con formato incorrecto en la ruta de la columna 1 de la línea 1 $

Este es mi fragmento:

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(); }

ACTUALIZAR

siempre este error no se trata de su json, podría deberse a su solicitud incorrecta, para un mejor manejo primero verifique su solicitud en el cartero si recibió respuesta y luego compare su respuesta json con su modelo si nada está mal, entonces este error proviene de su solicitud incorrecta, También podría ocurrir cuando su respuesta no es josn (en algunos casos, la respuesta tal vez sea html)


Además, este problema se produce cuando el tipo de contenido de respuesta no es application/json . En mi caso, el tipo de contenido de respuesta fue text/html y me enfrenté a este problema. Lo cambié a application/json luego funcionó.


En mi caso ; lo que resolvió mi problema fue .....

Es posible que tenga json así, las claves sin "comillas dobles ...

{nombre: "prueba", teléfono: "2324234"}

Por lo tanto, pruebe cualquier Validador Json en línea para asegurarse de tener la sintaxis correcta ...

Json Validator en línea


Este es un problema bien conocido y, en base a this respuesta, puede agregar setLenient :

Gson gson = new GsonBuilder() .setLenient() .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create(gson)) .build();

Ahora, si agrega esto a su actualización , le da otro error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

Este es otro error bien conocido que puede encontrar here (este error significa que la respuesta de su servidor no está bien formateada); Entonces cambie la respuesta del servidor para devolver algo:

{ android:[ { ver:"1.5", name:"Cupcace", api:"Api Level 3" } ... ] }

Para una mejor comprensión, compare su respuesta con la API de Github .

Sugerencia : para averiguar qué sucede con su request/response agregue HttpLoggingInterceptor en su HttpLoggingInterceptor .

Según this respuesta, su ServiceHelper sería:

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); }

Tampoco olvides agregar:

compile ''com.squareup.okhttp3:logging-interceptor:3.3.1''


Este problema comenzó a ocurrir de repente, así que estaba seguro de que podría haber alguna otra razón. Al excavar en profundidad, fue un problema simple donde utilicé http en la BaseUrl de Retrofit en lugar de https . Así que cambiarlo a https resolvió el problema para mí.


Hubo un error en la comprensión del tipo de retorno Solo agregue el encabezado y resolverá su problema

@Headers("Content-Type: application/json")


Me enfrenté a este problema e hice una investigación y no obtuve nada, así que lo intenté y finalmente, supe la causa de este problema. el problema en la API, asegúrate de tener un buen nombre de variable. Usé $ start_date y causó el problema, ¡así que intento $ startdate y funciona!

también asegúrese de enviar todos los parámetros que declaran en la API, por ejemplo, $ startdate = $ _POST [''startdate'']; $ enddate = $ _POST [''enddate''];

tienes que pasar estas dos variables desde la actualización.

así como si usa fecha en la declaración SQL, intente ponerlo dentro de '''' como ''2017-07-24''

Espero que te ayude.


Tuve el mismo problema junto con https://.com/a/57245058/8968137 y ambos se resolvieron después de arreglar google-services.json


si sus formatos JSON están bien, verifique las consultas de su base de datos. Intenta cambiarlos y vuelve a intentarlo