使用Retrofit 2.0获取MalformedJsonException

时间:2016-02-18 20:05:34

标签: android retrofit2

我正在创建一个从我的服务器获取数据的应用程序但是我收到以下异常...

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

我正在检索的JSON来自此网址http://soulappvm.cloudapp.net/SAService/Service.svc/userlist

JSON似乎格式正确,所以我不确定为什么我会收到此错误。

JSON

[{
    "Name": "Daniel1user",
    "Password": "40d5e24c5c906103a980ec7c69c100c5",
    "Address": "123 st"
}, {
    "Name": "Daniel2user",
    "Password": "90a1587cbe37d4a2a128ce758f338587",
    "Address": "1234 st"
}, {
    "Name": "Daniel3user",
    "Password": "f97c27c65d3af0d18657cbae16f9d57e",
    "Address": "ccc"
}, {
    "Name": "user1user",
    "Password": "def907bec025cd03bf738c3612bd7926",
    "Address": "ds"
}, {
    "Name": "user2user",
    "Password": "0fa04e1c4a5720195b106df9e746a72b",
    "Address": "ff"
}]

有没有办法打印我实际收到的对logcat的响应,看看出了什么问题?

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://soulappvm.cloudapp.net/SAService/Service.svc/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        MyApiEndpointInterface apiService = retrofit.create(MyApiEndpointInterface.class);
        Call<List<User>> call = apiService.getUsers();
                call.enqueue(new Callback<List<User>>() {
                    @Override

                    public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                        int statusCode = response.code();
                        System.out.println("response:  " + statusCode);

                    }

                    @Override
                    public void onFailure(Call<List<User>> call, Throwable t) {
                        System.out.println("It failed:  " + t);
                    }
                });

我的界面

public interface MyApiEndpointInterface {
    @GET("userlist")
    Call<List<User>> getUsers();
}

1 个答案:

答案 0 :(得分:0)

public class TestApi {

private final TaskTest mTask;
public static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
public TestApi(){
RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(ENDPOINT)
            .setConverter(new GsonConverter(gson))
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();
mTask = restAdapter.create(TaskTest.class);
}

public interface TaskTest{
    @GET(/test)
    void testResponse(Callback<List<test>> cb);
}
public void fetchTest(Callback<List<test>> cb){
    mTask.testResponse(cb);
}
}

呼叫应该是这样的

mTestApi.fetchTest(new Callback<List<test>>() {
        @Override
        public void success(List<test> tests, Response response) {

        }
        @Override
        public void failure(RetrofitError error) {

        }
    });