Mixed type lists

1 view
Skip to first unread message

The Noid

unread,
Jul 13, 2009, 1:18:03 PM7/13/09
to jsonmarshaller
Hi,

I've just found jsonmarshaller, and I really like it so far.
I was wondering how to handle mixed-type arrays. My Json contains
something like:

[14, "hg", "pep"]

Which is an array with numbers and strings. How would I go about
getting that into Java? Obviously I can't just specify it being a
List. Do I somehow need to make an interface with two subclasses? That
bit isn't documented yet... Or can I specify that it can just give me
the ArrayImpl object?

Regards,
Hylke

Pascal-Louis Perez

unread,
Jul 13, 2009, 1:32:19 PM7/13/09
to jsonmar...@googlegroups.com
It depends how much of a purist you are. Let me describe the "typical"
and the type safe answer.

1. typical

class MyEntity {
@Value(type = StringOrIntegerType.java)
List<Object> data;
}

where the type produces Integer or String objects when unmarshalling
(you can use the visitor pattern on Json.Value) and Json.Number and
Json.String when marshalling (you'll need to use an instanceof on
java.lang.Integer and java.lang.String here).

2. type safe

abstract class StringOrInteger {}
class StringOfStringOrInteger extends StringOrInteger { String value; ...
class IntegerOfStringOrInteger extends StringOrInteger { Integer value; ...

and then

class MyEntity {
@Value(type = StringOrIntegerType.java)
List<StringOrInteger> data;
}

note the bound change in the parameterisation of data's List type.

The StringOrIntegerType would essentially do the same as the previous
one, but here you could be type safe in both cases because you would
be able to implement the visitor pattern in the StringOrInteger class.

I'd personally recommend 1 since it is saner and less verbose, but
really, you should rethink mixing types... It smells fishy to me.

PL
--
Play, Learn, Earn - www.kaChing.com

The Noid

unread,
Jul 23, 2009, 4:49:38 PM7/23/09
to jsonmarshaller

> I'd personally recommend 1 since it is saner and less verbose, but
> really, you should rethink mixing types... It smells fishy to me.

Thanks for the quick reply. You where right. In the end I changed
things around a bit so there are only strings in the list. :)

Hylke
Reply all
Reply to author
Forward
0 new messages