169

What is this error ? How can I fix this? My app is running but can't load data. And this is my Error: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

This is my fragment :

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

a

UPDATE (read below text and find your problem)

  • most of the time, this error isn't about your json but it could be a incorrect http request such as a missing or a incorrect header, first check your request with postman to verify the servers response and servers response headers. if nothing is wrong then the error mostly came from your programmed http request, also it could because the servers response is not json (in some cases response could be html).
Chad
  • 2,938
  • 3
  • 27
  • 38
Erfan
  • 3,059
  • 3
  • 22
  • 49
  • Please show the output that you receive from `response.body()` – OneCricketeer Oct 07 '16 at 13:49
  • @cricket_007 i edit my question and show my results – Erfan Oct 08 '16 at 08:23
  • I didn't ask for images. I asked you to print out the value that is maybe returned from the server. – OneCricketeer Oct 08 '16 at 08:25
  • 1
    How do you print a value in Java? `System.out.println`, yes? In Android you can use the `Log` class, but that doesn't matter. You aren't getting data or an error is occurring at or around `JSONResponse jsonResponse = response.body();`. I don't know how to fix your error becuase it could be networking related. You should be able to inspect that value on your own. – OneCricketeer Oct 08 '16 at 08:50
  • I'm not a pro either, I'm trying to teach you how to debug any Java application, nothing really Android specific – OneCricketeer Oct 08 '16 at 16:00
  • I'm getting this issue for XML Response not for JSON Response. – Prasad Mar 08 '17 at 06:05
  • if your JSON formats are okay check your database queries. Try changing them and retry – Shabbir Ahmed Nov 09 '18 at 11:19
  • "also it could happened when your response not json" this phrase of your update helps me to fix. I forget to add "format = json" in my request object. – Manju Jan 28 '22 at 02:47

16 Answers16

281

This is a well-known issue and based on this answer you could add 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 with 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'
Amir
  • 16,067
  • 10
  • 80
  • 119
  • i edit my question look . but give same error : Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $ . also add error pic in question – Erfan Oct 13 '16 at 09:12
  • @erfan see edited answer; The issue is because your response from server is **Not** correct; remove " around attribute name and issue will be fixed. – Amir Oct 13 '16 at 09:46
  • 1
    { android:[ { ver:"1.5", name:"Cupcace", api:"Api Level 3" , pic:"pic2.jpg"} ] } this is my json exact like ur example and still same error :'( – Erfan Oct 13 '16 at 12:05
  • {"android": [ {"ver":"1.5","name":"Cupcace","api":"level3","pic":"bane.jpg"}]} , fix with this way – Erfan Oct 13 '16 at 12:22
  • 4
    use this and it will tell you immediately why your json is wrong http://jsonlint.com/ – Saik Caskey Feb 28 '17 at 16:56
  • Dear @Amir I am using retrofit in android apk to get a simple json like `{"ip":"192.167.1.15"}` from `Restful EJB web service with jboss EAP 7.1` in the backend. However I get “Expected BEGIN_OBJECT but was STRING at line 1 column 1” Please help me... This is my web service: @Stateless @Path("/getflashcard") public class GetFlashcard { @Interceptors(Validator.class) @GET @Produces(MediaType.APPLICATION_JSON) public String getFlashcard() { String jsonString = new JSONObject().put("ip", "192.167.1.15").toString(); return jsonString; } } – Hosein Aqajani Apr 02 '18 at 08:42
  • I used Call , and logged to see the output as response.body().string() with try/catch – ashishdhiman2007 May 21 '18 at 13:00
  • For me its simple. Just use the function echo json_encode($arrayName); instead of print_r($arrayName); With my php api. – Jevon May 23 '20 at 02:29
  • I am facing this same issue. But I tested my api in postman it's response is correct but why I am getting this error? can someone please tell me how to rectify it.. – Muthukumaaran Chandramohan Jun 26 '20 at 17:50
16

Using Moshi:

When building your Retrofit Service add .asLenient() to your MoshiConverterFactory. You don't need a ScalarsConverter. It should look something like this:

return Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ENDPOINT)
                .addConverterFactory(MoshiConverterFactory.create().asLenient())
                .build()
                .create(UserService::class.java)
Andre Thiele
  • 3,202
  • 3
  • 20
  • 43
15

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.

aligur
  • 3,387
  • 3
  • 34
  • 51
9

There was an error in understanding of return Type Just add Header and it will solve your problem

@Headers("Content-Type: application/json")
Jahanzaib
  • 154
  • 1
  • 3
5

I had same issue along with https://stackoverflow.com/a/57245058/8968137 and both solved after fixing the google-services.json

Raj
  • 747
  • 1
  • 9
  • 19
4

Im my case I forgot add @Headers("Accept: application/json") to Retrofit and have redirect on http page, with html in body razer json

Fortran
  • 2,218
  • 2
  • 27
  • 33
1

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.

Momen Zaqout
  • 1,508
  • 1
  • 16
  • 17
1

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...

Json Validator Online

shareef
  • 9,255
  • 13
  • 58
  • 89
1

I solved this problem very easily after finding out this happens when you aren't outputting a proper JSON object, I simply used the echo json_encode($arrayName); instead of print_r($arrayName); With my php api.

Every programming language or at least most programming languages should have their own version of the json_encode() and json_decode() functions.

Jevon
  • 295
  • 2
  • 13
1

For me all attempts with Moshi and Gson failed So I solved this issue with wrapper to get String response

private class FactoryWrapper(private val factory: Factory) : Factory() {
    override fun responseBodyConverter(
        type: Type,
        annotations: Array<out Annotation>,
        retrofit: Retrofit
                                      ): Converter<ResponseBody, *>? {
        return if (type.rawType == String::class.java) StringConverter()
        else factory.responseBodyConverter(type, annotations, retrofit)
    }

    private class StringConverter : Converter<ResponseBody, String> {
        override fun convert(value: ResponseBody): String {
            return value.string()
        }
    }
}

// to create factory
FactoryWrapper(MoshiConverterFactory.create(moshi).asLenient())

Not the best way but worked

Andrii Turkovskyi
  • 27,554
  • 16
  • 95
  • 105
0

This issue started occurring for me all of a sudden, so I was sure, there could be some other reason. On digging deep, it was a simple issue where I used http in the BaseUrl of Retrofit instead of https. So changing it to https solved the issue for me.

Shubhral
  • 334
  • 3
  • 15
0

Also worth checking is if there are any errors in the return type of your interface methods. I could reproduce this issue by having an unintended return type like Call<Call<ResponseBody>>

Otieno Rowland
  • 2,182
  • 1
  • 26
  • 34
0

Sometimes the error is displayed because the Relative link cannot find the data in the Base URL; I experienced the same issue and counterchecking that there is no error between the relative URL and base URL worked

Reny
  • 19
  • 5
0

I solve this issue after spending around 3 hrs. I have used postman for Api testing. there was mistake in json output. Please see images for more clarification (I got this error when output preview change from enter image description here JSON to HTML) Output Viewed in HTML

Output Viewed in JSON

rushab
  • 83
  • 1
  • 9
0

In case the answers from this thread doesn't help - check google-services.json file. In my case it contained a comment left from previous developer which caused the error.

soulflavacrew
  • 1,456
  • 1
  • 6
  • 3
0

Same issue after changing google-services.json

Solved:

project's build.gradle:

classpath 'com.android.tools.build:gradle:8.0.2'
classpath 'com.google.gms:google-services:4.3.15'

Module's(app) build.gradle:

android {
    namespace "com.example.myapp"
    // ...
}

dependencies {
    // ...
    implementation platform('com.google.firebase:firebase-bom:32.2.0')
    implementation 'com.google.firebase:firebase-analytics-ktx' // If you code in Kotlin language

// implementation 'com.google.firebase:firebase-analytics' // If you code in Java language implementation 'com.google.firebase:firebase-auth' implementation 'com.google.firebase:firebase-messaging' implementation 'com.google.android.gms:play-services-auth:20.6.0' // ... }

Hossein Kurd
  • 3,184
  • 3
  • 41
  • 71