tags:

views:

46

answers:

2

Let's say I have a class like this:

public class Person {
    private String firstName;
    private String lastName;
    ...
}

Then I create a map like this:

Map<Person, String> map = new HashMap<Person, String>();
map.put(new Person("Bob", "Builder"), "string1");
map.put(new Person("Bob", "NotBuilding"), "string2");

What should a valid json representation of the above look like? if it is indeed possible?

+1  A: 

You should have a serialization/deserialization mechanism for class Person first. For example each Person may have a unique id, which can be used as the map key. Java uses its hashCode() for serializing Person object to a key.

Mohsen
Good point, didn't think about hashCode()
digiarnie
A: 
{ "Persons" : { "string1" : { "class" : "Person", "firstName" : "Bob", "lastName" : "Builder" }, "string2" : { "class" : "Person", "firstName" : "Bob", "lastName" : "NotBuilding" } } }

This is only from a JSON stand point and assuming you name your map "Persons". You need to find a way to serialize and de-serialize but I guess you can find one in java.

Eric Fortin
Why would you map the value to the key as opposed to the key to the value? I guess my point is that the reason I asked my question was that converting an object such as 'Person' to a Json string would make for an invalid "name" in a 'name : value' pair due to the quotes embedded in the Person object.
digiarnie
Oh I got it the other way, although, I don't think it would be considered valid JSON to use the Person dictionary as a key.
Eric Fortin
It wouldn't be considered valid JSON to use the Person dictionary as a key unless you use some sort of a key for the Person object and one for the value like in: { "key" : { "class" : "Person" ...}, "value" : "string1" }, ...
Eric Fortin