Skip to content
Advertisement

How to generated the csv file from json data with Java?

I try to generate csv file from json type data. These are my json test data.

JavaScript

The problem is json array type "seriess” does not contain "notes" node in all every nodes. I made the below java codes to change this json data to csv file with header columns

JavaScript

But the incorrect results are shown like below,

JavaScript

The generated header columns does not contain distinct values. The header columns are added in duplicate. How can I generate the distinct header like below

JavaScript

Any idea?

Update Part

I try to extract data from the FRED (FEDERAL RESERVE BANK OF ST. LOUIS). FRED provide simple and convenient Python api like below,

JavaScript

But the java apis are deprecated, so I have to develop simple Java api which convert json values to csv file. I found the below Java codes with googling

JavaScript

To extract columns from json data JsonNode firstObject = jsonTree.elements().next(); return the first json node. But this line does not return notes column. because the first line does not contain the notes key value.

So I change this code line to following lines

JavaScript

But these lines throws the results which I do not expect. The repeated duplicated columns like below

JavaScript

I am totally stuck with this part.

Advertisement

Answer

Most probably it is easiest to write a bin type class like below :

JavaScript

Then you can Write :

JavaScript

csvWriterUtil is like below :

JavaScript

Full example is available in GitRepo

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement