如何使用自定义转换器?

时间:2018-01-24 10:00:05

标签: java retrofit simple-framework

我想从

解析时间
<monday>
    <item>
        <time>00:00:00</time>
    </item>
...
</monday>

一样长 我将物品定义为

@Root(strict = false) 
private static class Item {
     @Element(name = "time") 
     @Convert(TimeConverter.class) 
     private Long time;
}

我的转换器

public class TimeConverter implements org.simpleframework.xml.convert.Converter<Long> {

    SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");

    @Override 
    public Long read(InputNode node) throws Exception {
        try {
            String value = node.getValue();

          return df.parse(value).getTime();
        } catch (Exception e) {
          Log.e("mcheck", "read:  ", e);
          return 0L;
        }
    }

    @Override 
    public void write(OutputNode node, Long value) throws Exception {
        try {
            String v = df.format(new Date(value));
            node.setValue(v);
        } catch (Exception e) {
            Log.e("mcheck", "write:  ", e);
        }
    }
}

但是,当我解析它时,我会收到

  

retrofit.RetrofitError:java.lang.NumberFormatException:无效长:“00:00:00”

由于此异常未在转换器中的try-catch块中捕获,因此我认为解析器根本不会访问转换器。

我的改装1.9电话

OkHttpClient httpClient = new OkHttpClient();
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setEndpoint(url);
builder.setLogLevel(RestAdapter.LogLevel.FULL);
builder.setConverter(new SimpleXMLConverter());
builder.setClient(new OkClient(httpClient));
RestAdapter restAdapter = builder.build();
ChansonApi api = restAdapter.create(ChansonApi.class);
api.getStreamProgram(new Callback<StreamProgram>() {
    @Override
    public void success(StreamProgram streamProgram, Response response) {
        if(streamProgram!=null){
            Log.e("mcheck", "success:  "+streamProgram.getProgram());
        }
    }

    @Override 
    public void failure(RetrofitError error) {
        Log.e("mcheck", "failure:  ",error);
    }
});

1 个答案:

答案 0 :(得分:0)

问题出在proguard设置中。我不得不将TimeConverter添加到-keep类列表