b00blik
b00blik

Reputation: 31

Finding a way to parse multi-type JSON field

We have a JSON-answer from server, where we have array of byte arrays, but there is also can be a "None" string value instead of empty array. Example:

{'jsonrpc': '2.0', 'id': 31, 'result': {"bytes_arrays": [[21,99,165,243,25,210,14,121,120,39,22,102,59],[22,32,42,54,65,65,76,87],None]}

In my class I usually write something like this:

@JsonProperty("bytes_arrays")
    private List<byte[]> mArraysList = new ArrayList<>();

but of course, we'll have a parsing error for the last element with "None" value, because it's a string.

Are there any ways to extract multi-type field in this JSON? We use Jackson.

Upvotes: 2

Views: 362

Answers (1)

yglodt
yglodt

Reputation: 14551

There was a missing bracket at the end of your JSON string. Fixed and formatted it looks like this:

{
    'jsonrpc' : '2.0',
    'id' : 31,
    'result' : {
        "bytes_arrays" : [ 
                           [ 21, 99, 165, 243, 25, 210, 14, 121, 120, 39, 22, 102, 59 ], 
                           [ 22, 32, 42, 54, 65, 65, 76, 87 ], 
                           None 
                         ]
    }
}

Jackson should be able to parse it into a Map<String, Object>.

You can then check the type of Object with instanceof and put together your logic.

Upvotes: 1

Related Questions