-2

I want to parse the JSON data which response starts with the slash. I am using retrofit for parsing the data. thanks in advance. I have added the classes

/{
    "data": [
        {
            "id": "1",
            "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        },
        {
            "id": "2",
            "text": "Felis donec et odio pellentesque diam volutpat commodo sed. Non arcu risus quis varius quam quisque. Nibh nisl condimentum id venenatis a condimentum vitae. Vel pharetra vel turpis nunc eget. "
        },
        {
            "id": "3",
            "text": "Volutpat sed cras ornare arcu dui vivamus arcu felis bibendum. Lobortis mattis aliquam faucibus purus in. Aliquam sem fringilla ut morbi tincidunt augue interdum."
        },
        {
            "id": "4",
            "text": "Elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique. Bibendum at varius vel pharetra vel turpis nunc. Pellentesque sit amet porttitor eget dolor morbi non."
        },
        {
            "id": "5",
            "text": "Urna condimentum mattis pellentesque id. Ac tincidunt vitae semper quis. Massa tincidunt dui ut ornare lectus sit amet. Netus et malesuada fames ac turpis. Nulla facilisi cras fermentum odio eu feugiat pretium nibh."
        },
        {
            "id": "6",
            "text": "Tincidunt id aliquet risus feugiat in ante. Id donec ultrices tincidunt arcu non sodales neque sodales. Turpis massa tincidunt dui ut ornare lectus sit amet est. At ultrices mi tempus imperdiet nulla malesuada pellentesque elit."
        },
        {
            "id": "7",
            "text": "Fermentum posuere urna nec tincidunt praesent semper feugiat. Nulla facilisi etiam dignissim diam quis enim lobortis scelerisque fermentum. At auctor urna nunc id cursus metus aliquam eleifend mi."
        },
        {
            "id": "8",
            "text": "Quisque sagittis purus sit amet volutpat consequat mauris nunc congue. Malesuada fames ac turpis egestas sed. Volutpat ac tincidunt vitae semper. Aliquam nulla facilisi cras fermentum."
        }
    ]
}

I am getting this error

com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 2 path $

MainActivity



package com.basis.sliderapp.activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;

import com.basis.sliderapp.R;
import com.basis.sliderapp.adapter.DataAdapter;
import com.basis.sliderapp.apiCalls.ApiInterface;
import com.basis.sliderapp.model.BaseResponse;
import com.basis.sliderapp.model.Data;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private List<Data> searchResults = new ArrayList<>();
    private RecyclerView rec_data;
    private DataAdapter dataAdapter;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rec_data = findViewById(R.id.rec_data);

        dataAdapter = new DataAdapter( MainActivity.this,  searchResults);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, 1, false);
        rec_data.setLayoutManager(linearLayoutManager);
        rec_data.setAdapter(dataAdapter);

        getBasisData();

    }

    private void getBasisData() {

//        Gson gson = new GsonBuilder()
//                .setLenient()
//                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://git.io/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiInterface apiInterface = retrofit.create(ApiInterface.class);
        Call<BaseResponse> call = apiInterface.getData();
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {

                    BaseResponse baseResponse = response.body();
                    Log.d("list", baseResponse +"");

                    searchResults =  baseResponse.getDataList();
                    dataAdapter.setList(searchResults);

            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {

                Toast.makeText(getApplicationContext(), "Something is Wrong", Toast.LENGTH_SHORT).show();
            }
        });


    }
}

API Inteface====>

package com.basis.sliderapp.apiCalls;

import com.basis.sliderapp.model.BaseResponse;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface ApiInterface  {

    @GET("/fjaqJ/")
    Call<BaseResponse> getData();

}
Phantômaxx
  • 36,442
  • 21
  • 78
  • 108
Dharam Dutt Mishra
  • 411
  • 1
  • 4
  • 10

2 Answers2

2

I suppose there is no method in any json parser libraries which will search for the json as a substring of the source string.

If you have any rules for the upcoming json string, for example, it always starts with /, then you can just delete it by calling String.substring(1) (it will return as a result the new string without a first character of the source string.

EDIT:

class CustomConverterFactory : Converter.Factory() {

override fun responseBodyConverter(type: Type,
                                   annotations: Array<Annotation>,
                                   retrofit: Retrofit)
        : Converter<ResponseBody, *>? = ResponseBodyConverter<Any>(type)

override fun requestBodyConverter(type: Type, parameterAnnotations: Array<Annotation>,
                                  methodAnnotations: Array<Annotation>,
                                  retrofit: Retrofit)
        : Converter<*, RequestBody>? = RequestBodyConverter<Any>()

class ResponseBodyConverter<T> internal constructor(private val type: Type) : Converter<ResponseBody, T> {

    @Throws(IOException::class)
    override fun convert(value: ResponseBody): T? {
        // here we handle this '\' on the start of the server's response
        return DEFAULT_GSON_FACTORY.fromJson<T>(value.string().substring(1), type)
    }
}

class RequestBodyConverter<T> : Converter<T, RequestBody> {

    override fun convert(value: T): RequestBody = RequestBody.create(MEDIA_TYPE, DEFAULT_GSON_FACTORY.toJson(value))

}

companion object {
    private val MEDIA_TYPE = "application/json; charset=UTF-8".toMediaTypeOrNull()
    private val DEFAULT_GSON_FACTORY = Gson() // you can define here your own gson
}

}

After that you should use it in Retrofit builder:

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("your base url")
.client(okHttpClient)
.addConverterFactory(CustomConverterFactory())
.build();
RelaxedSoul
  • 591
  • 3
  • 9
0

as mentioned in this answer https://stackoverflow.com/a/40013869/5958272 use setLenient() property of gson to ignore the /

Gson gson = new GsonBuilder()
    .setLenient()
    .create();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .client(client)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();
Rahul
  • 26
  • 1
  • 6
  • hey @rahul I have already used this solution but still getting the same error. please give the specific solution for removing the slash( / ) from the JSON response and if possible pls let me know how to use the setLenient() method. – Dharam Dutt Mishra Sep 01 '19 at 07:34
  • you cannot remove the / from response . you can only direct the json parser to ignore this slash with setLenient() . can you share your code after making the above changes ? – Rahul Sep 01 '19 at 15:17
  • I am getting the response null coz of this slash so how do I parse it? can you please give me an example of how to ignore the slash by setLenient() method. – Dharam Dutt Mishra Sep 01 '19 at 18:49
  • check the code that i shared above .. you need to add converter factory in retrofit builder as i have shown . please provide your retrofit code so i can help further – Rahul Sep 02 '19 at 19:03