0

I'm using Jackson to read/write data from/into JSON files and I have an issue with the User POJO. It has a Map<Enum, Object> which is supposed to be the ways to contact the User (so it can have from 0 to 7, depending on the Enum). I want to be able to put ways to contact using a form in JSF.

I tried something like value="#{config.user.contacts[EMAIL_PRO]}" where of course EMAIL_PRO is an Enum (later, the user should be able to chose the Enum himself, but right now I try simple). But when I do so, the error is

Null key for a Map not allowed in JSON

which I understand, 'cause my debug says that the value returned is {null = null}. Now first question: since the map is empty, is JSF supposed to work simply like that? The key "EMAIL_PRO" doesn't exists yet, but shouldn't JSF make the work done for me, and put right value with the key?

The other question is much more about Jackson and Maps. As I said, my POJO User contains a Map, and the JSON file is a Map himself (containing multiple users).

Is it really possible to write a Map into this file using Jackson where the Map is Map<String, Object> and the Object contains a Map<Enum, Object>? And if yes, how?

Thanks for the help

PS: I cannot change either my APIs or my POJOs.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Ju Gaertner
  • 33
  • 1
  • 6

1 Answers1

0

I think this is a repeated post, see How to convert hashmap to JSON object in Java

And as it says on one of the responses:

Map<String, Object> data = new HashMap<String, Object>();
data.put( "name", "Mars" );
data.put( "age", 32 );
data.put( "city", "NY" );
JSONObject json = new JSONObject();
json.putAll( data );
System.out.printf( "JSON: %s", json.toString(2) );

output:

JSON: {
  "age": 32,
  "name": "Mars",
  "city": "NY"
}

You can also try to use Google's GSON.Google's GSON is the best library available to convert Java Objects into their JSON representation

  • The way you do it, I can understand. But you think it'll work if the Object contains a Map ? We're putting datas into a map, and then using ObjectMapper to write the map into a file, but I have some issues when the value contains a Map. – Ju Gaertner Jun 29 '17 at 11:40
  • I can't, I'm not the one who decides for that, and Jackson has been chosen for the project.. – Ju Gaertner Jun 29 '17 at 14:54
  • Try then with ObjectMapper, to read: `ObjectMapper mapper= new ObjectMapper(); ObjectYouWant =mapper.readValue({json},ObjectYouWant.class);` To write: `mapper.writeValue({outputJson}, objectYouWantToWrite);` – Java Gonzalez Arribas Jun 29 '17 at 15:05
  • This is done with com.fasterxml.jackson.databind.ObjectMapper – Java Gonzalez Arribas Jun 29 '17 at 15:06