Parsing JSON in Map <String, Entity> using FlexJSON

I am trying to parse a JSON structure like this:

{ "cars": { "112": { "make": "Cadillac", "model": "Eldorado", "year": "1998" }, "642": { "make": "Cadillac", "model": "Eldorado", "year": "1990" }, "9242": { "make": "Cadillac", "model": "Eldorado", "year": "2001" } }} 

I have a CarEntity class defined using makeName, model, year attributes defined and available through seters / getters.

I am trying to deserialize this JSON as follows:

  Map<String, CarEntity> deserialized = new JSONDeserializer<Map<String, CarEntity>>() .use("cars.values", Map.class) .deserialize(json); 

and it doesn’t work :( He deserializes it, but not in Map<String, CarEntity> , but rather in a deep map (something like Map<String, Map<String, Map<String, String>>> )

What am I doing wrong?

+1
java json deserialization flexjson
source share
3 answers

You problem is that your json has two cards. One that holds the "cars" key, and one that contains the actual CarEntity. Unfortunately, you cannot refer to one key on the map and assign types only on this key. Typically, the types of settings for values ​​for collections apply to all values ​​in the collection. You do not need to specify types for the first Map containing the "cars" key, as it will deserialize it by default.

 Map<String, CarEntity> deserialized = new JSONDeserializer<Map<String,Map<String, CarEntity>>>() .use("values.values", CarEntity.class ) .deserialize(json).get("cars"); 

The path "values.values" refers to the external values ​​of the map, and then moving the next values ​​of the map is all instances of CarEntity.

I considered changing the way expressions to be more expressive, allowing you to tweak a single value in a collection, but this increases the overhead of evaluating them and compatibility with feedback is a problem.

+2
source share

Most likely, you will be bitten by Java Type Erasure: the JSON library in question does not know the type that you need; everything he sees is equivalent to a Map. Therefore, you must somehow indicate the type of value. We hope that the FlexJSON documentation indicates how.

Alternatively, you can subclass the HashMap into your own type (MyEntityMap extends the HashMap), since then type information can be inferred from the common supertype; and passing MyEntityMap.class will give type information that most JSON libraries (at least Jackson and GSON) can use.

If they do not work, Jackson and GSON libraries can easily handle this use case; both have methods for determining typical types for deserialization.

+1
source share

Just add another get("cars") call, for example:

 Map<String, CarEntity> deserialized = new JSONDeserializer<Map<String, CarEntity>>() .use("cars.values", Map.class) .deserialize(json).get("cars"); 

The jSon string was probably serialized from the cars variable introduced as Map<String, CarEntity>

0
source share

All Articles