How do I map a heterogeneous JSON array to a Java object? How do I map a heterogeneous JSON array to a Java object? json json

How do I map a heterogeneous JSON array to a Java object?


Use JsonFormat and annotate your class with it where you specify shape as an ARRAY:

@JsonFormat(shape = JsonFormat.Shape.ARRAY)class MinuteCandle

Also, consider to use BigDecimal instead of double if you want to store a price.

See also:


I would do this in two steps:

  1. Read the JSON content into a list of List<Object> with Jackson.
  2. Convert each List<Object> into a MinuteCandle objectand collect these objects into a list of MinuteCandles.
import java.io.File;import java.util.ArrayList;import java.util.List;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.ObjectMapper;public class Main {    public static void main(String[] args) throws Exception {        ObjectMapper objectMapper = new ObjectMapper();        File file = new File("example.json");        List<List<Object>> lists = objectMapper.readValue(file, new TypeReference<List<List<Object>>>() {});        List<MinuteCandle> minuteCandles = new ArrayList<>();        for (List<Object> list : lists) {            minuteCandles.add(MinuteCandle.createFromList(list));        }    }}

The conversion from List<Object> to MinuteCandle (step 2 from above)could be achieved by adding a static method in your MinuteCandle class.

public static MinuteCandle createFromList(List<Object> list) {    MinuteCandle m = new MinuteCandle();    m.openTime = (Long) list.get(0);    m.openValue = Double.parseDouble((String) list.get(1));    m.highValue = Double.parseDouble((String) list.get(2));    m.lowValue = Double.parseDouble((String) list.get(3));    m.closeValue = Double.parseDouble((String) list.get(4));    m.volume = Double.parseDouble((String) list.get(5));    m.closeTime = (Long) list.get(6);    m.quoteAssetVolume = Double.parseDouble((String) list.get(7));    m.numberOfTrades = (Integer) list.get(8);    m.takerBuyBaseAssetVolume = Double.parseDouble((String) list.get(9));    m.takerBuyQuoteAssetVolume = Double.parseDouble((String) list.get(10));    m.someGarbageData = Double.parseDouble((String) list.get(11));    return m;}


Assuming the text stored in the file is valid JSON, similar to the solution in How to Read JSON data from txt file in Java? one can use com.google.gson.Gson as follows :

import com.google.gson.Gson;import java.io.FileReader;import java.io.Reader;public class Main {    public static void main(String[] args) throws Exception {        try (Reader reader = new FileReader("somefile.txt")) {            Gson gson = new Gson();            MinuteCandle[] features = gson.fromJson(reader, MinuteCandle[].class);        }    }}