2016-02-18 43 views
1

我创建一个应用程序,从我的服务器获取数据。但是,我发现了以下异常MalformedJsonException ...获取使用改造2.0

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

我检索JSON是从这个URL 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" 
}] 

有没有办法打印实际上,我recieving到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(); 
} 
+0

你可以创建一个自定义GSON解串器手动检查和反序列化日ËJSON收到:https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonDeserializer.html – Mauin

+0

@Mauin那么您是否可以给我怎样的例子我可以做到这一点? – M0rty

+0

这是一个为User对象创建自定义解串器的测试。在创建Gson实例后,您应该使用注册的反序列化器来初始化Retrofit。 http://pastebin.com/bQJywq0M – Mauin

回答

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) { 

     } 
    });