简体   繁体   中英

Jackson: instantiate list of Java objects from JSON objects with changing names?

I am trying to use Jackson to convert a JSON blob into an list of instantiated Java class objects. This is fairly straight forward whenever the JSON remains the same. However, each JSON object that comes back from the server starts with a unique UUID, which means that each object is different. It's like this:

{
    "863090b2-3d29-4829-9e01-5b03a6d5df04": {
        "name": "datasource 1",
        "dataSourceId": "863090b2-3d29-4829-9e01-5b03a6d5df04",
        "lastmodified": "2015-06-30T14:53:12"
    },
    "40de3a9e-e436-41b1-a37d-8c1d548293bc": {
        "name": "datasource 2",
        "dataSourceId": "40de3a9e-e436-41b1-a37d-8c1d548293bc",
        "lastmodified": "2015-06-30T14:52:46"
    },
    "f042db5f-455d-4edb-b8b5-610767735e64": {
        "name": "datasource 3",
        "dataSourceId": "f042db5f-455d-4edb-b8b5-610767735e64",
        "lastmodified": "2015-06-30T14:53:05"
    },
    "cd6323aa-ec27-4793-bb16-60729a556b97": {
        "name": "datasource 4",
        "dataSourceId": "cd6323aa-ec27-4793-bb16-60729a556b97",
        "lastmodified": "2015-06-30T14:52:55"
    }
}

Notice that each JSON object starts with a different name. If each JSON object were to be started with the same name (like "data") instead of with a UUID, this would be a cakewalk. Now I'm getting the following exception:

java.lang.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: [B@20e6c4dc; line: 1, column: 1]

This is the code segment I'm getting the exception from:

public List<Schema> getAllSchemas(String clientToken) {
    String endpoint = ALL_SCHEMAS_ROUTE + clientToken;
    byte[] responseBodyBytes = makeHttpRequest(endpoint, HttpMethod.GET, null).getBytes();
    List<Schema> allSchemas = null;
    try {
        allSchemas = objectMapper.readValue(responseBodyBytes,
                                            new TypeReference<List<Schema>>(){});
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return allSchemas;
}

Please note that Jackson will dejsonify a blob that contains only one of these objects, but will not do the entire list.

My limitations are these:

  • I have to use Jackson, because that's what is being used throughout the rest of the system.
  • I cannot change the way the server sends back the JSON to me.

Many thanks in advance for your help!

我能想到的最有前途的方法是将整个对象反序列化为Map<String, Schema> ,因此这些ID将不再被视为字段。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM