0

I'm trying to read data from this API https://coinmarketcap.com/api/

For this endpoint https://api.coinmarketcap.com/v2/ticker/. I'm having issues mapping the data field to a POJO. The field really contains an array of objects but in terms of the json it's not really defined as an array.

i.e. instead of

data: [{"id":"1","name":"some object"},{"id":"5","name":"another object"},...]

the json has named fields like so

data: {"1":{"id":"1","name":"some object"},"5":{"id":"5","name":"another object"},...}

I can manually parse this using

objectMapper.readTree(new URL("https://api.coinmarketcap.com/v2/ticker/"));

but is there a way automatically map these to a List?

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
user1531605
  • 87
  • 1
  • 5
  • 1
    It would be more natural to deserialise it to a `Map` from id to object. – teppic May 04 '18 at 00:31
  • I just visited that endpoint and it looks as though it is a list. (although the ticker doesn't -- which one are you interested in?) – tgdavies May 04 '18 at 00:39
  • @teppic I considered a Map but figure that i'm not interested in the key field, since i'm just going to iterate through the set and the id is already present within the json object. – user1531605 May 04 '18 at 00:46
  • @tgdavies, you're right i'm interested in the ticker endpoint – user1531605 May 04 '18 at 00:51

2 Answers2

2

You can parse it into a map (as @teppic said) and then get the map values as a list.

To deserialize into a map, you can see the answer from this question: Deserializing into a HashMap of custom objects with jackson

TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Theme.class);
HashMap<String, Theme> map = mapper.readValue(json, mapType);

Assuming you have a class called Item with the id and name fields, you can do this:

String json = "{\"1\":{\"id\":\"1\",\"name\":\"some object\"},\"5\":{\"id\":\"2\",\"name\":\"another object\"}}";

ObjectMapper mapper = new ObjectMapper();

// create your map type <String, Item>
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Item.class);
HashMap<String, Item> map = mapper.readValue(json, mapType);

// get the list
List<Item> list = new ArrayList<Item>(map.values());

System.out.println(list);

Output:

[Item [id=1, name=some object], Item [id=2, name=another object]]

Your other option would be a custom deserializer, or reading the tree as you mentioned.

tima
  • 1,498
  • 4
  • 20
  • 28
-1

try this

String json = "[{\"name\":\"Steve\",\"lastname\":\"Jobs\"}]"; JsonArray jArray = (JsonArray)new JsonParser().parse(json);

String sName = jArray.get(0).getAsJsonObject().get("name").getAsString()); String sLastName = jArray.get(0).getAsJsonObject().get("lastname").getAsString());

see you later.