将json数组反序列化为java对象保持列表

时间:2017-05-04 09:47:57

标签: java arrays json spring jackson2

好的,所以我一直在搞乱这一点。我得到一个json数组,其中包含如下所示的对象:[{ "id": "1", "name": "some name", "url": "some url", "active": true }, { "id": "2", "name": "some other name", "url": "some other url", "active": true } ]"

现在,我希望能够将该数组反序列化为一个包含数组中对象列表的java对象。我已经制作了一个自定义反序列化器,如下所示:

public class ListSerializer extends JsonDeserializer<List<Provider>>{

private static final long serialVersionUID = 9114152571639338391L;

@Override
public List<Provider> deserialize(JsonParser jsonParser, 
DeserializationContext arg1) throws IOException, JsonProcessingException {
// TODO Auto-generated method stub
final ObjectCodec objectCodec = jsonParser.getCodec();
final JsonNode listOrObjectNode = objectCodec.readTree(jsonParser);
final List<Provider> result = new ArrayList<Provider>();
for (JsonNode node : listOrObjectNode) {
  result.add(objectCodec.treeToValue(node, Provider.class));
}
  return result;
}



}

持有该列表的类看起来像这样:

public class ProviderList {

@JsonDeserialize(using = ListSerializer.class)
private List<Provider> providerList;

 public List<Provider> getProviderList() {
  return providerList;
}

public void setProviderList(final List<Provider> providerList) {
  this.providerList = providerList;
 }

}

现在,我知道这可能是一个愚蠢的方法,但长话短说,这只是需要。我显然做错了,因为我得到了这个错误:

  

无法反序列化实例   com.wirelesscar.trailser.v1_0.domain.ProviderList出自START_ARRAY   令牌在[来源:   [{ “ID”: “1”, “名称”: “Posttrack”, “URL”: “HTTP:\ dev.posttrack.com”, “活性”:真},{ “ID”: “2”,”命名 “:” Trackunit”, “URL”: “HTTP:\ dev.trackunit.com”, “主动”:真正}]。   line:1,column:1]

所以我的问题。这可能吗?我在哪里错了。

先谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用TypeReference包装器直接反序列化到列表。

@Data
public class Provider {
    private Long id;
    private String name;
    private String url;
    private boolean active;
}

@Data
public class ProviderList {
    List<Provider> providerList;
}

public class JsonTest {

    @Test
    public void  test() {
        String json = "[{\n" +
                "        \"id\": \"1\",\n" +
                "        \"name\": \"some name\",\n" +
                "        \"url\": \"some url\",\n" +
                "        \"active\": true\n" +
                "    }, {\n" +
                "        \"id\": \"2\",\n" +
                "        \"name\": \"some other name\",\n" +
                "        \"url\": \"some other url\",\n" +
                "        \"active\": true\n" +
                "    }\n" +
                "]";

        ObjectMapper mapper = new ObjectMapper();
        try {
            List<Provider> providerList = mapper.readValue(json, new TypeReference<List<Provider>>(){});
            for (Provider provider : providerList) {
                System.out.println(provider);
            }

            ProviderList list = new ProviderList();
            list.setProviderList(providerList);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}