I want to create a nested JSON from a flattened CSV:
CSV:
name address_city address_state
John Mumbai MH
John Bangalore KA
Bill Chennai TN
JSON:
[
{
"name": "John",
"address": [
{
"city": "Mumbai",
"state": "MH"
},
{
"city": "Bangalore",
"state": "KA"
}
]
},
{
"name": "Bill",
"address": [
{
"city": "Chennai",
"state": "TN"
}
]
}
]
I'm using univocity parser with @Nested annotation like this:
@Nested(headerTransformer = AddressTypeTransformer.class, args = "address")
private Address address;
and I'm getting JSON output as below, which has the address object and not array which is perfectly fine:
[
{
"name": "John",
"address": {
"city": "Mumbai",
"state": "MH"
}
},
{
"name": "John",
"address": {
"city": "Mumbai",
"state": "MH"
}
},
{
"name": "Bill",
"address": {
"city": "Chennai",
"state": "TN"
}
}
]
But when i change the code to make the address as array:
@Nested(headerTransformer = AddressTypeTransformer.class, args = "address")
private Address[] address;
I get following error:
Exception in thread "main" com.univocity.parsers.common.DataProcessingException: Unable to instantiate class '[Lcom.ss.beans.Address;'
Internal state when error was thrown: line=2, column=0, record=1, charIndex=58, headers=[id, name, address_city, address_state],
Why the @Nested annotation is not working with arrays/lists? How can I solve this problem? Is there any other way to solve this problem without using univocity?
PS: I'm asking this question after following the reply from @Jeronimo Backes in this post: Convert CSV data into nested json objects using java library
Here is my approach:
The test data (in my case, the fields are tab-separated):
The imports I used:
The processing code:
The
SourceRecord
bean is as follows. Note that we do not need anything other than the basic@Nested
annotation, here:Here are the output
Name
andAddress
beans. Note I am using the field nameaddresses
(notaddress
) in theName
bean:And the
Address
bean - this is used both for the final output and also when reading the source file (hence the annotations are needed):The final JSON is: