The JSON output that I am looking for is
{[[1, 1.5, "String1"], [-2, 2.3, "String2"]]}
So I want to have an Array of Arrays and the inner array is storing different types.
How should I store my variables so I can create such JSON in Scala?
I thought of List of Tuples. However, all the available JSON libraries try to convert a Tuple to a map instead of an Array. I am using json4s
library.
Here is a custom serializer for those inner arrays using
json4s
:The custom serialiser converts
JArray
into a tuple and back again. This will be used wherever the Scala object being read or written has a value of the appropriate tuple type.To test this against the sample input I have modified it to make it valid JSON by adding a field name:
I have defined a container class to match this:
The name of the class is not relevant but the field name
data
must match the JSON field name. This usesVector
rather thanArray
becauseArray
is really a Java type rather than a Scala type. You can useList
if preferred.If you prefer to use a custom class for the data rather than a tuple, the code looks like this: