我有一个类 DbRecord
public class DbRecord {
@JsonField(name="on_duties")
List<OnDutyElement> onDuties;
@JsonField(name = "date_time")
DateTime dateTime;
当我尝试序列化此类的对象时,LoganSquare 不包含 dateTime 字段。
生成的 JSON:{:"2015-12-21T11:32:17.503-05:00","on_duties":[{...从这里一切正常
最佳答案
如果所有 JSON 字段名称都是小写且带有下划线,您可以这样定义 fieldNamingPolicy。
@JsonObject(fieldNamingPolicy = JsonObject.FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
public class DbRecord {
@JsonField
List<OnDutyElement> onDuties;
@JsonField
DateTime dateTime;
如果您还没有为 DateTime 设置 TypeConverter,LoganSquare 现在允许您像那样在 JsonField 注释中定义 TypeConverter
@JsonField(typeConverter = DateTimeConverter.class)
DateTime time;
和日期时间转换器
public class DateTimeConverter implements TypeConverter<DateTime> {
@Override
public DateTime parse(JsonParser jsonParser) throws IOException {
String dateString = jsonParser.getValueAsString(null);
try {
DateTime dateTime = new DateTime(dateString);
return dateTime.changeTimeZone(TimeZone.getTimeZone("UTC"), TimeZone.getDefault());
} catch (RuntimeException runtimeException) {
runtimeException.printStackTrace();
return null;
}
}
@Override
public void serialize(DateTime object, String fieldName, boolean writeFieldNameForObject, JsonGenerator jsonGenerator) throws IOException {
jsonGenerator.writeStringField(fieldName, object.format("YYYY-MM-DDThh:mm:ss"));
}
关于android - LoganSquare 在生成的 Json 中不包含字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34400383/