1

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?

2
  • don't use Person (an object) as the hash key, give the Person some id, and use that as a key. Store the Person itself somewhere else (also keyed with the same id). Commented Aug 12, 2010 at 3:55
  • I'm creating a custom json framework so I don't really have a way to enforce what people may or may not do. I was just curious as to how the above map would be represented not so much the validity of how the map is used even though I do understand your point. Commented Aug 12, 2010 at 4:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
{ "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.

3 Comments

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.
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.
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" }, ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.