杰克逊阵列到 Pojo 不只在 Android 上工作
Posted
技术标签:
【中文标题】杰克逊阵列到 Pojo 不只在 Android 上工作【英文标题】:Jackson Array to Pojo Not Working Only on Android 【发布时间】:2019-12-17 03:05:15 【问题描述】:我想将 json 数组转换为 POJO,它在 JVM 上运行但在 android 上失败
这是我的pojo:
package com.binance.api.client.domain.market;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
@JsonPropertyOrder()
@JsonIgnoreProperties(ignoreUnknown = true)
public class Lilin
public Long openTime;
public String open;
public String high;
public String low;
public String close;
public String volume;
public Long closeTime;
public String quoteAssetVolume;
public Long numberOfTrades;
public String takerBuyBaseAssetVolume;
public String takerBuyQuoteAssetVolume;
然后手动测试一下:
public void testCandlestickDeserializer()
final String candlestickJson = "[\n" +
" 1499040000000,\n" +
" \"0.01634790\",\n" +
" \"0.80000000\",\n" +
" \"0.01575800\",\n" +
" \"0.01577100\",\n" +
" \"148976.11427815\",\n" +
" 1499644799999,\n" +
" \"2434.19055334\",\n" +
" 308,\n" +
" \"1756.87402397\",\n" +
" \"28.46694368\",\n" +
" \"17928899.62484339\"\n" +
" ]";
ObjectMapper mapper = new ObjectMapper();
try
Lilin candlestick = mapper.readValue(candlestickJson, Lilin.class);
System.out.println(candlestick);
catch (IOException e)
System.err.println(e);
在 JVM 上尝试没有错误,但在 Android 上运行时出现此错误:
Cannot deserialize value of type `java.lang.Long` from String "0.01634790": not a valid Long value
@JsonPropertyOrder()
注释似乎在 Android 上无法正常工作
【问题讨论】:
【参考方案1】:您可能错过了定义属性排序,例如来自文档:
例子:
// ensure that "id" and "name" are output before other properties
@JsonPropertyOrder( "id", "name" )
// order any properties that don't have explicit setting using alphabetic order
@JsonPropertyOrder(alphabetic=true)
//This annotation may or may not have effect on deserialization: for basic JSON handling there is no effect, but for other supported data types (or structural conventions) there may be.
来源:https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonPropertyOrder.html
【讨论】:
谢谢,添加@JsonPropertyOrder("openTime", "open", "high", "low", "close", "volume","closeTime","quoteAssetVolume","numberOfTrades","takerBuyBaseAssetVolume","takerBuyQuoteAssetVolume")
现在可以使用了以上是关于杰克逊阵列到 Pojo 不只在 Android 上工作的主要内容,如果未能解决你的问题,请参考以下文章
如何更改杰克逊以检测 POJO 中的所有字段,而不仅仅是公共字段?
无法反序列化从 Springboot POST 映射函数上的 Angular http post 请求发送的 POJO