我得到以下API的响应
"[{"num":0.705251649,"host":"a"},{"num":0.6223491728,"host":"b"},{"num":0.6486086175,"host":"c"},{"num":0.6595501527,"host":"d"},{"num":0.5766476765,"host":"e"},{"num":0.6029071212,"host":"f"}]";
数据类型
java.lang.String
如何有效地提取像
这样的值- 第一个包含最高num的块,提取host
- 最后一个包含最小数目的块,提取host
我写了如下代码:
public class Myclass{
String resp = "[{"num":0.705251649,"host":"a"},{"num":0.6223491728,"host":"b"},{"num":0.6486086175,"host":"c"},{"num":0.6595501527,"host":"d"},{"num":0.5766476765,"host":"e"},{"num":0.6029071212,"host":"f"}]"
ObjectMapper objectMapper = new ObjectMapper();
Prediction[] langs = objectMapper.readValue(resp, Prediction[].class);
List<Prediction> langList = new ArrayList(Arrays.asList(langs));
}
class Prediction {
@JsonProperty("num")
BigDecimal num;
@JsonProperty("host")
String host;
}
I am getting below error:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.x.y.z.Prediction[]`: no String-argument constructor/factory method to deserialize from String value ('[{"num":0.705251649,"host":"a"},{"num":0.6223491728,"host":"b"},{"num":0.6486086175,"host":"c"},{"num":0.6595501527,"host":"d"},{"num":0.5766476765,"host":"e"},{"num":0.6029071212,"host":"f"}]')
at [Source: (String)""[{"num":0.705251649,"host":"a"},{"num":0.6223491728,"host":"b"},{"num":0.6486086175,"host":"c"},{"num":0.6595501527,"host":"d"},{"num":0.5766476765,"host":"e"},{"num":0.6029071212,"host":"f"}]; line: 1, column: 1]
你可以直接在列表中隐藏,如下所示,
ObjectMapper mapper = new ObjectMapper();
String str = "[{"num":0.705251649,"host":"a"},{"num":0.6223491728,"host":"b"},{"num":0.6486086175,"host":"c"},{"num":0.6595501527,"host":"d"},{"num":0.5766476765,"host":"e"},{"num":0.6029071212,"host":"f"}]";
List<Prediction> predictions = mapper.readValue(str, new TypeReference<List<Prediction>>() {});
System.out.println(predictions.size());
预测类:
public class Prediction {
@JsonProperty("num")
BigDecimal num;
@JsonProperty("host")
String host;
}
所有我尝试过的代码:
public class Test {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String str = "[{"num":0.705251649,"host":"a"},{"num":0.6223491728,"host":"b"},{"num":0.6486086175,"host":"c"},{"num":0.6595501527,"host":"d"},{"num":0.5766476765,"host":"e"},{"num":0.6029071212,"host":"f"}]";
List<Prediction> predictions = mapper.readValue(str, new TypeReference<List<Prediction>>() {});
System.out.println(predictions.get(0).getNum()+" : "+predictions.get(0).getHost());
}
public static class Prediction {
@JsonProperty("num")
BigDecimal num;
@JsonProperty("host")
String host;
public BigDecimal getNum() {
return num;
}
public String getHost() {
return host;
}
}
}
输出:
0.705251649 : a