无法使用Gson Retrofit将yyyy-MM-ddTHH:mm:SS转换为日期

时间:2017-05-30 07:52:13

标签: android date gson

我正在使用Gson来解析响应中的值。我的回答看起来像(邮递员):

{
  "payLoad": {
   "totalItems": 1,
   "totalPages": 1,
   "items": [
    {
      "id": "f13e9f94fbb144d2956326f6c50f4d29",
      "rechargeStatus": "PENDING",
      "dateOfRequest": "2017-05-30T11:29:33",
      "amount": 1,
      "category": "Electricity",
      "operator": "Electricity Limited",
      "whereToRecharge": "212323232"
    }
   ]
  },
  "success": true,
  "timestamp": "2017-05-30T13:08:18"
}

当我在AS中记录我的回复时,我有:

Fetch Recharge Payload : {totalItems=1.0, totalPages=1.0, items=
[{uuid=f12e9f94fbb144d2956326f6c50f4d29, rechargeStatus=PENDING,
dateOfRequest=2017-05-30T11:29:33, amount=1.0, category=Electricity,
operator=Electricity Limited, whereToRecharge=212323232}]}

我已经为日期格式添加了GsonBuilder,如下所示(作为sugessted here):

Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
            .create();

解析数据如下:

Map<String, Object> map = (Map<String, Object>) myResponse.payLoad;
List<Recharge> rechargeTable = stringToArray(String.valueOf(map.get("items")), Recharge[].class);

...
public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
    T[] arr = new Gson().fromJson(s, clazz);
    return Arrays.asList(arr);
}

我得到的错误是:

com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException:
Unterminated object at line 1 column 94 path $[0].dateOfRequest

主要问题是解析日期。我是否需要添加更多配置?

额外问题:   - 为什么我的整数转换为double?   - 为什么从字符串值中删除双引号?

1 个答案:

答案 0 :(得分:1)

尝试以您的方式实施此示例。

<强>摇篮

compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'

<强>接口

public interface ServiceInterface {
@GET(HttpConstants.USERDATAJSON)
    Call<ListData>taskData(@Query("method")String method,@Query("stdID")int stdID);
}

服务类

public class ServiceClass {
    static ServiceInterface serviceInterface;
//    public static final String baseUrl= HttpConstants.BASE_URL_GEONAME;
    public static final String baseUrl= HttpConstants.baseUrl;

    public static ServiceInterface connection(){
        if(serviceInterface==null){
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient();
            client.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Response response=chain.proceed(chain.request());
                    return response;
                }
            });
            Retrofit retrofit = new Retrofit.Builder()
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(baseUrl)
                    .build();
            serviceInterface=retrofit.create(ServiceInterface.class);
        }
        return serviceInterface;
    }
}

用法

public void getTaskData(){
    ServiceInterface serviceInterface=ServiceClass.connection();
    Call<ListData> call=serviceInterface.taskData("getAllUsersSimple",0);
    call.enqueue(new Callback<ListData>() {
        @Override
        public void onResponse(Response<ListData> response, Retrofit retrofit) {
            Log.v("@@@Response",""+response.toString());
            if(response.isSuccess()){
                listData=response.body();
                dataList=listData.getData();
                printStudentDetails(dataList);

            }
        }

        @Override
        public void onFailure(Throwable t) {
            Log.v("@@@Failure"," Message"+t.getMessage());
        }
    });
}

public void printStudentDetails(List<DataPojo> list){
    Log.v("@@@WWe","Student List");
    for (DataPojo dataPojo:list){
        Log.d("Student ID ",dataPojo.getUserId());
        Log.d("Student Name ",dataPojo.getUserName());
        Log.d("Student Age ",dataPojo.getUserAge());
    }
}

<强> POJO的

public class ListData {

    @SerializedName("data")
    @Expose
    private List<DataPojo> data = null;
    @SerializedName("code")
    @Expose
    private Integer code;
    @SerializedName("message")
    @Expose
    private String message;

    public List<DataPojo> getData() {
        return data;
    }

    public void setData(List<DataPojo> data) {
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

public class DataPojo {

    @SerializedName("user_id")
    @Expose
    private String userId;
    @SerializedName("user_name")
    @Expose
    private String userName;
    @SerializedName("user_age")
    @Expose
    private String userAge;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }

}

有关更多参考资料,请访问我的完整示例 https://github.com/pratikvyas1991/NetworkingExample/tree/master/app