How to Map Two Tables To One Class in Fluent NHibernate?

How do I serialize a java.util.Map with the Jackson JSON processor if the key is a custom class?

  • I am using Jackson 1.8.2, I have a POJO where one of the attributes is Map<MyKey, String> and MyKey is a class that has two attributes, a Long and an Integer.  When Jackson serializes the POJO that contains the Map<MyKey, String> I get{ “MyKey@12f34f”, “stringValue”}  for the map.   I can not find a concrete example  anywhere *that works* so instead I would get something like {{“LongAttr”:123,”IntegerAtt”:456}, “stringValue”}.  I can not get @JsonSerialize(asKey=…) or @JsonSerialize(keyUsing=…) to work on the attribute in the POJO that  is the map (seems to be ignored by Jackson, the custom JsonSerializer I have never gets executed) .  What is the proper way to do this?

  • Answer:

    Sorry, you can't do this. Look at the JSON spec:   http://www.json.org/ It's very simple. The first words of the first bullet point say it clearly: "A collection of name/value pairs". Keep in mind that JSON is basically lifted from Javascript syntax for object and array literals. Your map in Java is mapped to/from a Javascript object, when and if it is evaluated in a browser context. A Javascript object has fields, and the fields have names. Names can't be objects, they are strings. Jackson is doing what it can here, resorting to toString(). You can, of course, create an object where the fields have names that are JSON strings. And, of course, this would be insane. On second thought, you probably can't even do that, since field names obviously can't hold arbitrary characters. So this would require some string encoding of JSON that obeys Javascript syntax for field names! Is there a quora board for mad computer science?

Kjetil Valstadsve at Quora Visit the source

Was this solution helpful to you?

Other answers

As says, in JSON, keys must be strings. However, you can still represent your map in JSON, just not as a JSON object: [ [ {"LongAttr":123, "IntegerAtt":456}, "stringValue" ], [ {"LongAttr":129, "IntegerAtt":442}, "somethingelse" ], ... ] You can even probably persuade Jackson to do this.

Toby Thain

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.