Retrofit和Gson上的MalformedJsonException

时间:2017-07-06 06:31:12

标签: android gson retrofit

我试图进行改装调用,并且我收到了MalformedJsonException。

这是我的电话:

String idFoto = "1ead0a1f-bbc4-46bd-901c-7988c0e6c68b";
Retrofit retrofit = new Retrofit.Builder()
     .baseUrl(Global.URL_BASE)
     .addConverterFactory(GsonConverterFactory.create())
     .build();
FotosAPI service = retrofit.create(FotosAPI.class);
Call<String> obtenerFotoCall = service.getFoto(Global.getToken(), idFoto);

这是我的界面:

public interface FotosAPI {
     @GET(Global.URL_FOTO + "{id}")
     Call<String> getFoto(@Header("Authorization") String token, @Path("id") String id);
}

call enqueue进入onFailure方法,错误是&#34; com.google.gson.stream.MalformedJsonException:使用JsonReader.setLenient(true)接受第1行第2列路径中的格式错误的JSON $&#34;

我做了更改以设置宽松,如下所示:

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

然后,我有一个不同的错误:&#34; com.google.gson.stream.MalformedJsonException:第1行第1行路径的预期值$&#34;

我认为错误可能是在idFoto字符串值的Gson转换中,但我不知道出了什么问题。

有人能帮助我吗?

谢谢你们!

2 个答案:

答案 0 :(得分:0)

请检查您从服务器获取的JSON,在我的情况下,我从服务器获取的JSON无效。

尝试从Postman或其他工具中检查您的JSON。

答案 1 :(得分:0)

就像M D所说的那样(非常感谢你!),解决办法就是为ToStringCorverterFactory改变GsonConverter。

这是我使用的课程:

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class ToStringConverterFactory extends Converter.Factory {
    private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        if (String.class.equals(type)) {
            return new Converter<ResponseBody, String>() {
                @Override
                public String convert(ResponseBody value) throws IOException {
                    return value.string();
                }
            };
        }
        return null;
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,
                                                          Annotation[] methodAnnotations, Retrofit retrofit) {

        if (String.class.equals(type)) {
            return new Converter<String, RequestBody>() {
                @Override
                public RequestBody convert(String value) throws IOException {
                    return RequestBody.create(MEDIA_TYPE, value);
                }
            };
        }
        return null;
    }
}

然后您只需要将改装构建器更改为:

Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(Global.URL_BASE)
                        .addConverterFactory(new ToStringConverterFactory())
                        .build();