Reputation: 4570
I have a use case where I must parse JSON into primitive values in Java. I have instructive fields embedded in the JSON that informs my parsing which primitive to deserialize to. These primitive types must be added to an array of some length.
So I may have some JSON like this:
"primitives" : [
{
"valueType" : "int",
"value" : 3
},
{
"valueType" : "double",
"value" : 4
},
]
I have written the code to properly parse this JSON into two primitives, one int and double with values 3 and 4. However, because I am adding them to an ArrayList which expects Objects they are autoboxed into Java's Integer and Double types. I thought of using a regular Java Array but there is still the problem of specifying the element type like Object[] arr
where I have the same problem, or int[]
where I am being too specific.
Is there some functionality within Java that can allow me to parse this JSON to the correct Array of primitives.
One solution I have considered is an object that has all the different primitives as properties but this seems like too much complexity if a language level path is available.
Upvotes: 0
Views: 412
Reputation: 4403
Assuming that it is important to keep the original ordering (thus a single array), and that keeping track of the type is important, and that using a JSON parser is unavailable, I would consider something like the following.
enum ValueType { INT, DOUBLE, FLOAT };
static abstract class ParsedValue<T>
{
private final T data;
private final ValueType type;
public ParsedValue(T val, ValueType t)
{
data = val;
type = t;
}
public ValueType getType()
{
return type;
}
public T getValue()
{
return data;
}
}
static class IntParsedValue extends ParsedValue<Integer>
{
public IntParsedValue(Integer val)
{
super(val, ValueType.INT);
}
}
static class DoubleParsedValue extends ParsedValue<Double>
{
public DoubleParsedValue(Double val)
{
super(val, ValueType.DOUBLE);
}
}
public static void main(String[] args)
{
List<ParsedValue<?>> lst = new ArrayList<>();
Random rnd = new Random();
for (int i = 0; i < 25; ++i) {
ParsedValue<?> pv;
if (rnd.nextInt(2) == 0) {
pv = new IntParsedValue(rnd.nextInt(500));
}
else {
pv = new DoubleParsedValue(rnd.nextDouble());
}
lst.add(pv);
}
for (ParsedValue<?> pv : lst) {
switch (pv.getType()) {
case INT:
System.out.println("Integer: " + pv.getValue());
break;
case DOUBLE:
System.out.println("Double: " + pv.getValue());
break;
case FLOAT:
//...
break;
}
}
}
Upvotes: 2