So I've got this huge JSON file available from which I need to extract data. The JSON format goes something like this:
{
"enabled":true,
"contentMetadataPartial":
{
"customTags":
{
"tag1":"value1"
}
},
"simulatedChanges":
[
3000,
2500,
400
],
"simulatedUpdateMetadata":
[
{
"customTags":
{
"tag1":"value1",
},
"assetName":"asset1234",
},
{
"duration":1111,
"encodedRate":3333,
}
]
}
To read it I was trying to create a class to the map the keys and objects. Something like this, similar to this question:
public class ConfigData
{
private Boolean enabled;
private class ContentMetadataPartial
{
private class CustomTags
{
String tag1;
}
}
int[] simulatedChanges = new int[3];
//problem here
}
But I'm getting stuck at the array, which contains more objects not just simple basic data types.
The JSON file is huge and has similar type of items all over it. I'm fairly new with this and may be doing some mistake. Any help towards right direction is appreciated. Thanks!
You need a classes structure, not all in one:
ConfigData:
package com.example.gson;
import java.util.List;
public class ConfigData {
private Boolean enabled;
private ContentMetadataPartial contentMetadataPartial;
private List<Integer> simulatedChanges = null;
private List<SimulatedUpdateMetadatum> simulatedUpdateMetadata = null;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public ContentMetadataPartial getContentMetadataPartial() {
return contentMetadataPartial;
}
public void setContentMetadataPartial(ContentMetadataPartial contentMetadataPartial) {
this.contentMetadataPartial = contentMetadataPartial;
}
public List<Integer> getSimulatedChanges() {
return simulatedChanges;
}
public void setSimulatedChanges(List<Integer> simulatedChanges) {
this.simulatedChanges = simulatedChanges;
}
public List<SimulatedUpdateMetadatum> getSimulatedUpdateMetadata() {
return simulatedUpdateMetadata;
}
public void setSimulatedUpdateMetadata(List<SimulatedUpdateMetadatum> simulatedUpdateMetadata) {
this.simulatedUpdateMetadata = simulatedUpdateMetadata;
}
#Override
public String toString() {
return "ConfigData [enabled=" + enabled + ", contentMetadataPartial=" + contentMetadataPartial
+ ", simulatedChanges=" + simulatedChanges + ", simulatedUpdateMetadata=" + simulatedUpdateMetadata
+ "]";
}
}
ContentMetadataPartial:
package com.example.gson;
public class ContentMetadataPartial {
private CustomTags customTags;
public CustomTags getCustomTags() {
return customTags;
}
public void setCustomTags(CustomTags customTags) {
this.customTags = customTags;
}
}
CustomTags:
package com.example.gson;
public class CustomTags {
private String tag1;
public String getTag1() {
return tag1;
}
public void setTag1(String tag1) {
this.tag1 = tag1;
}
}
SimulatedUpdateMetadatum:
package com.example.gson;
public class SimulatedUpdateMetadatum {
private CustomTags customTags;
private String assetName;
private Integer duration;
private Integer encodedRate;
public CustomTags getCustomTags() {
return customTags;
}
public void setCustomTags(CustomTags customTags) {
this.customTags = customTags;
}
public String getAssetName() {
return assetName;
}
public void setAssetName(String assetName) {
this.assetName = assetName;
}
public Integer getDuration() {
return duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public Integer getEncodedRate() {
return encodedRate;
}
public void setEncodedRate(Integer encodedRate) {
this.encodedRate = encodedRate;
}
}
GsonMain:
package com.example.gson;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.example.gson.ConfigData;
import com.google.gson.Gson;
public class GsonMain {
private static final String jsonFile = "files/input.json";
public static void main(String[] args) {
String content = readFile(jsonFile);
ConfigData conf = new Gson().fromJson(content, ConfigData.class);
System.out.println(conf);
}
private static String readFile(String filename) {
BufferedReader br = null;
FileReader fr = null;
StringBuilder content = new StringBuilder();
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
content.append(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return content.toString();
}
}
And your Json well formed:
{
"enabled":true,
"contentMetadataPartial":
{
"customTags":
{
"tag1":"value1"
}
},
"simulatedChanges":
[
3000,
2500,
400
],
"simulatedUpdateMetadata":
[
{
"customTags":
{
"tag1":"value1"
},
"assetName":"asset1234"
},
{
"duration":1111,
"encodedRate":3333
}
]
}
I have used this web to generate the classes.
package com.webom.practice;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Sample {
public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
public static void main(String[]args) {
String Jsondata="{\r\n" +
" \"enabled\":true,\r\n" +
" \"contentMetadataPartial\":\r\n" +
" {\r\n" +
" \"customTags\":\r\n" +
" {\r\n" +
" \"tag1\":\"value1\"\r\n" +
" }\r\n" +
" },\r\n" +
" \"simulatedChanges\":\r\n" +
" [\r\n" +
" 3000,\r\n" +
" 2500,\r\n" +
" 400\r\n" +
" ],\r\n" +
" \"simulatedUpdateMetadata\":\r\n" +
" [\r\n" +
" {\r\n" +
" \"customTags\":\r\n" +
" {\r\n" +
" \"tag1\":\"value1\",\r\n" +
" },\r\n" +
" \"assetName\":\"asset1234\",\r\n" +
" },\r\n" +
" {\r\n" +
" \"duration\":1111,\r\n" +
" \"encodedRate\":3333,\r\n" +
" }\r\n" +
" ]\r\n" +
"}\r\n" ;
JSONObject json = new JSONObject(Jsondata);
System.out.println(json);
Map<String,Object> dataConversion=Sample.jsonToMap(json);
System.out.println(dataConversion);
}
}
Related
First of all, i'm completely noob in Java... and i need help to modify a piece of code.
The current code, write data to a CSV file and i need to modify it to save to JSON format, but using java.util.PriorityQueue, java.io.BufferedReader and java.io.PrintWriter. Can anyone help me to achieve this ?
Here is the code:
Route.java file:
import Exceptions.FailedCheckException;
import java.time.ZonedDateTime;
public class Route implements Comparable<Route> {
private Integer id;
private String name;
private Coordinates coordinates;
private java.time.ZonedDateTime creationDate;
private Location from;
private Location to;
private Long distance;
java.time.ZonedDateTime getCreationDate() {
return creationDate;
}
#Override
public String toString() {
return "Route{" +
"id=" + id +
", name='" + name + '\'' +
", coordinates=" + coordinates +
", creationDate=" + creationDate +
", from=" + from +
", to=" + to +
", distance=" + distance +
'}';
}
public String toCSVfile() {
String CSV = id + "," + name + "," + coordinates.getX() + "," + coordinates.getY() + "," + creationDate + ",";
if (from != null)
CSV += from.getX() + "," + from.getY() + "," + from.getZ() + "," + from.getName() + ",";
else
CSV += "null,,,,";
CSV += to.getX() + "," + to.getY() + "," + to.getZ() + "," + to.getName() + ",";
CSV += distance != null ? distance : "null";
return CSV;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getDistance() {
return distance;
}
public void setCreationDate(ZonedDateTime creationDate) {
this.creationDate = creationDate;
}
public void setFrom(Location from) {
this.from = from;
}
public void setTo(Location to) {
this.to = to;
}
public void setDistance(Long distance) {
this.distance = distance;
}
public static Checker<Long> distanceCheck = (Long L) -> {
if (L == null) return null;
else if (L > 1) return L;
throw new FailedCheckException();
};
public static Checker<Integer> idCheck = (Integer I) -> {
if (I != null && I > 0) return I;
else throw new FailedCheckException();
};
public static Checker<String> nameCheck = (String S) -> {
if (S != null && S.length() != 0) return S;
else throw new FailedCheckException();
};
#Override
public int compareTo(Route route) {
int result = getName().compareTo(route.getName());
if (result == 0 && getDistance() != null && route.getDistance() != null) {
result = getDistance().compareTo(route.getDistance());
}
return result;
}
}
And here is the SaveManagement.java file:
import Exceptions.FailedCheckException;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.util.Collections;
import java.util.Scanner;
/**
* Class operating with files
*/
public class SaveManagement {
private static File file;
public static void setFile(File file) {
SaveManagement.file = file;
}
/**
* file saving in CSV format
*/
public static void saveToFile(Collection c) {
if (file == null)
file = new File("save.csv");
try (FileWriter fileWriter = new FileWriter(file)) {
for (Route r : c.list) {
fileWriter.write(r.toCSVfile() + "\n");
}
} catch (IOException e) {
System.out.println("File Access Error");
}
}
/**
* Returns a collection from a saved file
*/
#NotNull
public static Collection listFromSave() {
Collection collection = new Collection();
try (Scanner scan = new Scanner(file)) {
String[] args;
for (int lineNum = 1; scan.hasNext(); lineNum++) {
try {
String line = scan.nextLine();
args = line.split(",", 14);
Route route = new Route();
int id = Route.idCheck.checker(Integer.parseInt(args[0]));
if (collection.searchById(id) == null)
route.setId(id);
else {
System.out.println("Invalid id received");
throw new FailedCheckException();
}
route.setName(Route.nameCheck.checker(args[1]));
int cx = Coordinates.xCheck.checker(Integer.parseInt(args[2]));
Long cy = Coordinates.yCheck.checker(Long.parseLong(args[3]));
route.setCoordinates(new Coordinates(cx, cy));
ZonedDateTime dateTime = ZonedDateTime.parse(args[4]);
route.setCreationDate(dateTime);
if (!args[5].equals("null")) {
Long fromX = Location.xyzCheck.checker(Long.parseLong(args[5]));
Long fromY = Location.xyzCheck.checker(Long.parseLong(args[6]));
long fromZ = Location.xyzCheck.checker(Long.parseLong(args[7]));
route.setFrom(new Location(fromX, fromY, fromZ, args[8]));
}
Long toX = Location.xyzCheck.checker(Long.parseLong(args[9]));
Long toY = Location.xyzCheck.checker(Long.parseLong(args[10]));
long toZ = Location.xyzCheck.checker(Long.parseLong(args[11]));
route.setTo(new Location(toX, toY, toZ, args[12]));
if (!args[13].equals("null")) {
Long dis = Route.distanceCheck.checker(Long.parseLong(args[13]));
route.setDistance(dis);
}
collection.list.add(route);
} catch (ArrayIndexOutOfBoundsException | DateTimeParseException | NumberFormatException | FailedCheckException e) {
System.out.println("\u001B[31m" + "Error reading file, line: " + "\u001B[0m" + lineNum);
}
}
} catch (FileNotFoundException e) {
System.out.println("\u001B[31m" + "File Access Error" + "\u001B[0m");
}
Collections.sort(collection.list);
return collection;
}
}
FileWriter should be changed to PrintWriter, Scanner with BufferedReader and i don't know how to implement java.util.PriorityQueue.
Thank you!
Edit:
Should i import java.util.PriorityQueue on Route.java and change
public String toCSVfile() {
to
public String toJSONfile() {
Requirement:
I have two csv file input.csv and output.csv
The goal is to read the data rows from input.csv, then do some processing on it and if the processing fails then write the failed row of csv to output.csv
Initially input.csv have some data and output.csv is blank.
Here is the main class file:
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class UploadDocUsingCsv {
private static final String INPUT_CSV_FILE_PATH = "resources/input.csv";
private static final String OUTPUT_CSV_FILE_PATH = "resources/output.csv"; // this file only contain data whose upload is failed
public static void main(String args[]) {
try (
Reader reader4Input = Files.newBufferedReader(Paths.get(INPUT_CSV_FILE_PATH));
Reader reader4Output = Files.newBufferedReader(Paths.get(OUTPUT_CSV_FILE_PATH))
) {
// Read Input File
CsvToBean csvToBean4Input;
CsvToBeanBuilder csvToBeanBuilder4Input = new CsvToBeanBuilder(reader4Input);
csvToBeanBuilder4Input.withType(DocumentDetail.class);
csvToBeanBuilder4Input.withIgnoreLeadingWhiteSpace(true);
csvToBeanBuilder4Input.withSkipLines(0);
csvToBean4Input = csvToBeanBuilder4Input.build();
// Read Output File
CsvToBean csvToBean4Output;
CsvToBeanBuilder csvToBeanBuilder4Output= new CsvToBeanBuilder(reader4Output);
csvToBeanBuilder4Output.withType(DocumentDetail.class);
csvToBeanBuilder4Output.withIgnoreLeadingWhiteSpace(true);
csvToBeanBuilder4Output.withSkipLines(1); // skip header
csvToBean4Output = csvToBeanBuilder4Output.build();
// Declare Set to contain DocumentDetail object whose data could not be sent
HashSet<DocumentDetail> documentDetailsNotSent = new HashSet<DocumentDetail>();
// Call method to upload the document from input file
Iterator<DocumentDetail> csvDocumentDetailIterator = csvToBean4Input.iterator();
DocumentDetail csvHeader = csvDocumentDetailIterator.next(); // skip the header
// documentDetailsNotSent.add(csvHeader);
while (csvDocumentDetailIterator.hasNext()) {
DocumentDetail documentDetail = csvDocumentDetailIterator.next();
System.out.println(documentDetail);
documentDetailsNotSent.add(documentDetail);
}
// Call method to upload the document from output file
csvDocumentDetailIterator = csvToBean4Output.iterator(); // java.lang.RuntimeException: Error capturing CSV header!
while (csvDocumentDetailIterator.hasNext()) {
DocumentDetail documentDetail = csvDocumentDetailIterator.next();
System.out.println(documentDetail);
documentDetailsNotSent.add(documentDetail);
}
Writer writer4Output = Files.newBufferedWriter(Paths.get(OUTPUT_CSV_FILE_PATH));
// write the documentDetail objects that are not uploaded to output file
ArrayList<DocumentDetail> documentDetailNotSetList = new ArrayList<DocumentDetail>(documentDetailsNotSent);
documentDetailNotSetList.add(0, csvHeader);
ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(DocumentDetail.class);
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer4Output)
.withMappingStrategy(mappingStrategy)
.build();
beanToCsv.write(documentDetailNotSetList);
writer4Output.close();
} catch (Exception e){
System.out.println(e);
}
}
}
DocumentDetail class used as Bean is here:
import com.opencsv.bean.CsvBindByPosition;
import java.util.Objects;
public class DocumentDetail {
#CsvBindByPosition(position = 0)
private String contractId;
#CsvBindByPosition(position = 1)
private String partyId;
#CsvBindByPosition(position = 2)
private String contractBranch;
#CsvBindByPosition(position = 3)
private String customerName;
#CsvBindByPosition(position = 4)
private String vertical;
#CsvBindByPosition(position = 5)
private String referenceContractId;
#CsvBindByPosition(position = 6)
private String bankFlowNo;
#CsvBindByPosition(position = 7)
private String payoutCategory;
#CsvBindByPosition(position = 8)
private String camNo;
#CsvBindByPosition(position = 9)
private String camStatus;
#CsvBindByPosition(position = 10)
private String folderName;
#CsvBindByPosition(position = 11)
private String documentName;
#CsvBindByPosition(position = 12)
private String pdfName;
public String getContractId() {
return contractId;
}
public void setContractId(String contractId) {
this.contractId = contractId;
}
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
}
public String getContractBranch() {
return contractBranch;
}
public void setContractBranch(String contractBranch) {
this.contractBranch = contractBranch;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getVertical() {
return vertical;
}
public void setVertical(String vertical) {
this.vertical = vertical;
}
public String getReferenceContractId() {
return referenceContractId;
}
public void setReferenceContractId(String referenceContractId) {
this.referenceContractId = referenceContractId;
}
public String getBankFlowNo() {
return bankFlowNo;
}
public void setBankFlowNo(String bankFlowNo) {
this.bankFlowNo = bankFlowNo;
}
public String getPayoutCategory() {
return payoutCategory;
}
public void setPayoutCategory(String payoutCategory) {
this.payoutCategory = payoutCategory;
}
public String getCamNo() {
return camNo;
}
public void setCamNo(String camNo) {
this.camNo = camNo;
}
public String getCamStatus() {
return camStatus;
}
public void setCamStatus(String camStatus) {
this.camStatus = camStatus;
}
public String getFolderName() {
return folderName;
}
public void setFolderName(String folderName) {
this.folderName = folderName;
}
public String getDocumentName() {
return documentName;
}
public void setDocumentName(String documentName) {
this.documentName = documentName;
}
public String getPdfName() {
return pdfName;
}
public void setPdfName(String pdfName) {
this.pdfName = pdfName;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DocumentDetail that = (DocumentDetail) o;
return contractId.equals(that.contractId) &&
partyId.equals(that.partyId) &&
contractBranch.equals(that.contractBranch) &&
customerName.equals(that.customerName) &&
vertical.equals(that.vertical) &&
referenceContractId.equals(that.referenceContractId) &&
bankFlowNo.equals(that.bankFlowNo) &&
payoutCategory.equals(that.payoutCategory) &&
camNo.equals(that.camNo) &&
camStatus.equals(that.camStatus) &&
folderName.equals(that.folderName) &&
documentName.equals(that.documentName) &&
pdfName.equals(that.pdfName);
}
#Override
public int hashCode() {
return Objects.hash(contractId, partyId, contractBranch, customerName, vertical, referenceContractId,
bankFlowNo, payoutCategory, camNo, camStatus, folderName, documentName, pdfName);
}
#Override
public String toString() {
return "DocumentDetail{" +
"contractId='" + contractId + '\'' +
", partyId='" + partyId + '\'' +
", contractBranch='" + contractBranch + '\'' +
", customerName='" + customerName + '\'' +
", vertical='" + vertical + '\'' +
", referenceContractId='" + referenceContractId + '\'' +
", bankFlowNo='" + bankFlowNo + '\'' +
", payoutCategory='" + payoutCategory + '\'' +
", camNo='" + camNo + '\'' +
", camStatus='" + camStatus + '\'' +
", folderName='" + folderName + '\'' +
", documentName='" + documentName + '\'' +
", pdfName='" + pdfName + '\'' +
'}';
}
}
Input.csv is here
CONTRACT _ID,PARTY_ID ,CONTRACT_BRANCH ,CUSTOMER_NAME,VERTICAL ,REFERENCE_CONTRACT_ID ,BANK FLOW NO,PAYOUT CATEGORY,CAM_NO,CAM_STATUS ,FOLDER _NAME ,Document Name,PDF_NAME
133336,362177,xyz,qwe fghfg,fgh,NG233112344,958875934,Purchase Invoice,NA,APPROVED,dfgdfg Construction_dfg,PAYMENT VOUCHER,9588759.pdf
The question is how to solve the java.lang.RuntimeException: Error capturing CSV header! while calling csvToBean4Output.iterator();
I have solved the problem by checking for the output.csv is empty or not.
Here is the code:
boolean empty = (new File(OUTPUT_CSV_FILE_PATH)).length() == 0;
if(!empty){
csvDocumentDetailIterator = csvToBean4Output.iterator();
while (csvDocumentDetailIterator.hasNext()) {
DocumentDetail documentDetail = csvDocumentDetailIterator.next();
logger.info(documentDetail);
boolean isSent = commonMethods.uploadDoc(documentDetail);
logger.info("isSent: " + isSent);
if(!isSent){
documentDetailsNotSent.add(documentDetail);
}
}
}
I have a scenario where I get a string output from a service that returns a folder structure as below
id=0c06c81c8052324b;name=Documentation;type=root;|id=0b06c81c80524a87;name=ABC;type=folder;parent=0c06c81c8052324b;|id=0b06c81c80524837;name=Admin;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052483d;name=Admin 2.0;type=folder;parent=0b06c81c80524837;|id=0b06c81c8052483a;name=Panel;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052484a;name=VCM;type=folder;parent=0b06c81c8052483a;|id=0c06c81c80269e63;name=Invoices;type=root;|id=0b06c81c8026a008;name=other;type=folder;parent=0c06c81c80269e63;|id=0b06c81c8027a600;name=Workflow;type=folder;parent=0b06c81c8026a008;|id=0b06c81c8027a601;name=Worksheet;type=folder;parent=0b06c81c8027a600;|id=0c06c81c8051c7d3;name=Receipts;type=root;|id=0b06c81c80545f32;name=VR_2;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f33;name=VR_3;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f30;name=VR_1;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c8053486d;name=VR;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f31;name=test2;type=folder;parent=0b06c81c8053486d;|id=0c06c81c8051c7d2;name=Source;type=root;|id=0b06c81c80524a8b;name=gem;type=folder;parent=0c06c81c8051c7d2;|id=0b06c81c80521681;name=Code;type=folder;parent=0b06c81c80524a8b;|id=0b06c81c8051cba7;name=pfm;type=folder;parent=0b06c81c80524a8b;
I was able to write a recursive logic to parse that string to come up with a structure as below:
Children of DCMGEN -> Documentation, ID: 0c06c81c8052324b
Children of DCMGEN -> Invoices, ID: 0c06c81c80269e63
Children of DCMGEN -> Source, ID: 0c06c81c8051c7d2
Children of DCMGEN -> Receipts, ID: 0c06c81c8051c7d3
Children of Documentation -> ABC, ID: 0b06c81c80524a87
Children of ABC -> Admin, ID: 0b06c81c80524837
Children of ABC -> Panel, ID: 0b06c81c8052483a
Children of Admin -> Admin 2.0, ID: 0b06c81c8052483d
Children of Panel -> VCM, ID: 0b06c81c8052484a
Children of Invoices -> other, ID: 0b06c81c8026a008
Children of other -> Workflow, ID: 0b06c81c8027a600
Children of Workflow -> Worksheet, ID: 0b06c81c8027a601
Children of Source -> gem, ID: 0b06c81c80524a8b
Children of gem -> Code, ID: 0b06c81c80521681
Children of gem -> pfm, ID: 0b06c81c8051cba7
Children of Receipts -> VR_2, ID: 0b06c81c80545f32
Children of Receipts -> VR_3, ID: 0b06c81c80545f33
Children of Receipts -> VR_1, ID: 0b06c81c80545f30
Children of Receipts -> VR, ID: 0b06c81c8053486d
Children of VR -> test2, ID: 0b06c81c80545f31
However, I want to create a folder structure from it on my local machine but am not able to create it recursively. Looking for some clues to solve this recursive problem. Can anyone please help ??
DCMGEN
Documentation
ABC
Admin
Admin 2.0
Panel
VCM
Invoices
other
Workflow
Worksheet
Source
gem
Code
pfm
Receipts
VR
test2
VR_1
VR_2
VR_3
Below is my code to get this far (with the help of some other thread on StackOverflow):
MegaMenuDTO.java
import java.util.ArrayList;
import java.util.List;
public class MegaMenuDTO {
private String Id;
private String name;
private String parentId;
private String type;
private List<MegaMenuDTO> childrenItems;
public MegaMenuDTO() {
this.Id = "";
this.name = "";
this.parentId = "";
this.childrenItems = new ArrayList<MegaMenuDTO>();
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public List<MegaMenuDTO> getChildrenItems() {
return childrenItems;
}
public void setChildrenItems(List<MegaMenuDTO> childrenItems) {
this.childrenItems = childrenItems;
}
public void addChildrenItem(MegaMenuDTO childrenItem){
if(!this.childrenItems.contains(childrenItem))
this.childrenItems.add(childrenItem);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
// return "MegaMenuDTO [Id=" + Id + ", name=" + name + ", parentId="
// + parentId + ", childrenItems=" + childrenItems + "]";
return "[name=" + name + ", childrenItems=" + childrenItems + "]";
}
}
MenuHelper.java
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MenuHelper {
private static final String TEMP_ROOT_FOLDER = "DCMGEN";
private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
private static final String FOLDERTREE_STR = "foldertree=";
private static final String RECORD_ELEMENT_DELIM = "[\\|]+";
private static final String SEPARATOR = System.getProperty("file.separator");
private static Map<String, List<MegaMenuDTO>> parentChildMap = new LinkedHashMap<String, List<MegaMenuDTO>>();
private static Map<String, String> idNameMap = new LinkedHashMap<String, String>();
//Test this helper class....
public static void main(String[] args) throws IOException {
final String FOLDER_STRUCTURE = "id=0c06c81c8052324b;name=Documentation;type=cabinet;|id=0b06c81c80524a87;name=ABC;type=folder;parent=0c06c81c8052324b;|id=0b06c81c80524837;name=Admin;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052483d;name=Admin 2.0;type=folder;parent=0b06c81c80524837;|id=0b06c81c8052483a;name=Panel;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052484a;name=VCM;type=folder;parent=0b06c81c8052483a;|id=0c06c81c80269e63;name=Invoices;type=cabinet;|id=0b06c81c8026a008;name=other;type=folder;parent=0c06c81c80269e63;|id=0b06c81c8027a600;name=Workflow;type=folder;parent=0b06c81c8026a008;|id=0b06c81c8027a601;name=Worksheet;type=folder;parent=0b06c81c8027a600;|id=0c06c81c8051c7d3;name=Receipts;type=cabinet;|id=0b06c81c80545f32;name=VR_2;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f33;name=VR_3;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f30;name=VR_1;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c8053486d;name=VR;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f31;name=test2;type=folder;parent=0b06c81c8053486d;|id=0c06c81c8051c7d2;name=Source;type=root;|id=0b06c81c80524a8b;name=gem;type=folder;parent=0c06c81c8051c7d2;|id=0b06c81c80521681;name=Code;type=folder;parent=0b06c81c80524a8b;|id=0b06c81c8051cba7;name=pfm;type=folder;parent=0b06c81c80524a8b;";
System.out.println("Temp folder : " + System.getProperty(JAVA_IO_TMPDIR));
List<FolderObj> folders = MenuHelper.parseResponseString(FOLDER_STRUCTURE);
if(folders != null) {
List<MegaMenuDTO> menuDTOList = MenuHelper.prepareMenu(folders);
List<File> rootDirs = new ArrayList<>();
File rootDir = new File(System.getProperty(JAVA_IO_TMPDIR) + SEPARATOR + TEMP_ROOT_FOLDER);
//Check and Delete the root folder, if present, before processing.
if(rootDir.exists()) {
rootDirs.add(rootDir);
for(File file : rootDirs) {
recursivelyDelete(file);
}
}
//Create a fresh root dir.
rootDirs.clear();
rootDir = createTempRootDir(TEMP_ROOT_FOLDER);
rootDirs.add(rootDir);
//System.out.println("Tree : " + menuDTOList);
for(MegaMenuDTO mmd: menuDTOList){
printMenu(mmd, "\t");
captureIdNameMap(mmd);
printPaths(mmd, TEMP_ROOT_FOLDER + SEPARATOR + mmd.getName());
}
for (Map.Entry<String, List<MegaMenuDTO>> entry : parentChildMap.entrySet()) {
String key = entry.getKey();
List<MegaMenuDTO> value = entry.getValue();
for(MegaMenuDTO dto : value) {
if(idNameMap.get(key) == null) {
System.out.println("Children of " + key + " -> " + dto.getName() + ", ID: " + dto.getId());
} else {
System.out.println("Children of " + idNameMap.get(key) + " -> " + dto.getName() + ", ID: " + dto.getId());
}
}
}
}
}
public static List<FolderObj> parseResponseString(final String input) {
if(input == null) {
return null;
}
List<FolderObj> menuList = new ArrayList<>();
String[] parsedValues = input.split(RECORD_ELEMENT_DELIM);
for(short i=0; i < parsedValues.length; i++) {
menuList.add(digest(filterValue(parsedValues[i])));
}
return menuList;
}
public static String filterValue(String input) {
if(input == null) {
return input;
}
if(input.contains(FOLDERTREE_STR)) {
input = input.substring(input.indexOf(FOLDERTREE_STR) + FOLDERTREE_STR.length());
}
return input;
}
public static FolderObj digest(String input) {
if(input == null) {
return null;
}
Map<String, String> holder = new HashMap<>();
String [] keyVals = input.split(";");
for(String keyVal : keyVals) {
String [] parts = keyVal.split("=");
holder.put(parts[0], parts[1]);
}
FolderObj folderObj = null;
String childId = null;
String name = null;
String type = null;
String parentId = null;
for(Map.Entry<String, String> entry : holder.entrySet()) {
String key = entry.getKey();
if(key.equals("id")) {
childId = entry.getValue();
} else if(key.equals("name")) {
name = entry.getValue();
} else if(key.equals("type")) {
type = entry.getValue();
} else if(key.equals("parent")) {
parentId = entry.getValue();
}
folderObj = new FolderObj(childId, parentId, name, type);
}
return folderObj;
}
public static List<MegaMenuDTO> prepareMenu(List<FolderObj> folderList) {
// Arrange String corresponds to the Id
Map<String, MegaMenuDTO> megaMenuMap = new HashMap<>();
// populate a Map
for(FolderObj folderObj: folderList){
// ----- Child -----
MegaMenuDTO mmdChild;
if(megaMenuMap.containsKey(folderObj.getChildId())){
mmdChild = megaMenuMap.get(folderObj.getChildId());
}
else{
mmdChild = new MegaMenuDTO();
megaMenuMap.put(folderObj.getChildId(),mmdChild);
}
mmdChild.setId(folderObj.getChildId());
mmdChild.setParentId(folderObj.getParentId());
mmdChild.setName(folderObj.getName());
mmdChild.setType(folderObj.getType());
// no need to set ChildrenItems list because the constructor created a new empty list
// ------ Parent ----
MegaMenuDTO mmdParent;
if(megaMenuMap.containsKey(folderObj.getParentId())){
mmdParent = megaMenuMap.get(folderObj.getParentId());
}
else{
mmdParent = new MegaMenuDTO();
megaMenuMap.put(folderObj.getParentId(),mmdParent);
}
mmdParent.setId(folderObj.getParentId());
// mmdParent.setParentId(null);
mmdParent.addChildrenItem(mmdChild);
}
// Get the root
List<MegaMenuDTO> menuList = new ArrayList<MegaMenuDTO>();
for(MegaMenuDTO megaMenuDTO : megaMenuMap.values()){
if(megaMenuDTO.getParentId() == null)
menuList.add(megaMenuDTO);
}
return menuList;
}
private static void printMenu(MegaMenuDTO dto, String tabValue) {
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
System.out.println(tabValue + childDTO.getName());
tabValue = "\t" + tabValue;
printMenu(childDTO, tabValue);
}
}
private static void captureIdNameMap(MegaMenuDTO dto) throws IOException {
idNameMap.put(dto.getId(), dto.getName());
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
idNameMap.put(childDTO.getId(), childDTO.getName());
captureIdNameMap(childDTO);
}
}
private static void printPaths(MegaMenuDTO dto, String name) throws IOException {
if(dto.getParentId() == null) {
if(parentChildMap.get("ROOT") == null) {
List<MegaMenuDTO> parentList = new ArrayList<MegaMenuDTO>();
parentList.add(dto);
parentChildMap.put("ROOT", parentList);
} else {
List<MegaMenuDTO> parentList = parentChildMap.get("ROOT");
parentList.add(dto);
parentChildMap.put("ROOT", parentList);
}
}
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
if (parentChildMap.get(childDTO.getParentId()) == null) {
List<MegaMenuDTO> parentList = new ArrayList<MegaMenuDTO>();
parentList.add(childDTO);
parentChildMap.put(childDTO.getParentId(), parentList);
} else {
List<MegaMenuDTO> parentList = parentChildMap.get(childDTO.getParentId());
parentList.add(childDTO);
parentChildMap.put(childDTO.getParentId(), parentList);
}
System.out.println(name + SEPARATOR + childDTO.getName() + ", ParentId : " + childDTO.getParentId());
createTempRootDir(name + SEPARATOR + childDTO.getName());
name = name + SEPARATOR + childDTO.getName();
printPaths(childDTO, name);
}
}
public static File createTempRootDir(String name) throws IOException {
final File sysTempDir = new File(System.getProperty(JAVA_IO_TMPDIR));
File newTempDir = new File(sysTempDir, name);
if (newTempDir.mkdirs()) {
return newTempDir;
} else {
throw new IOException("Failed to create temp dir named " + newTempDir.getAbsolutePath());
}
}
/**
* Recursively delete file or directory
*
* #param fileOrDir
* the file or dir to delete
* #return true iff all files are successfully deleted
*/
public static void recursivelyDelete(File fileOrDir) throws IOException {
Path directory = Paths.get(fileOrDir.getAbsolutePath());
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
}
Finally got it to work after reading up more on recursion. Below is the new updated code for anyone trying to do something similar. Not claiming that this is the most efficient or shortest code possible but the best I could come up with. If someone has an improved version, I would be very happy to see that.
MenuHelper.java
public class MenuHelper {
private static final String TEMP_ROOT_FOLDER = "DCMGEN";
private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
private static final String FOLDERTREE_STR = "foldertree=";
private static final String RECORD_ELEMENT_DELIM = "[\\|]+";
private static final String SEPARATOR = System.getProperty("file.separator");
private static Map<String, List<MegaMenuDTO>> parentChildMap = new LinkedHashMap<String, List<MegaMenuDTO>>();
private static Map<String, String> idNameMap = new LinkedHashMap<String, String>();
//Test this helper class....
public static void main(String[] args) throws IOException {
final String FOLDER_STRUCTURE = "id=0c06c81c8052324b;name=Documentation;type=cabinet;|id=0b06c81c80524a87;name=ABC;type=folder;parent=0c06c81c8052324b;|id=0b06c81c80524837;name=Admin;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052483d;name=Admin 2.0;type=folder;parent=0b06c81c80524837;|id=0b06c81c8052483a;name=Panel;type=folder;parent=0b06c81c80524a87;|id=0b06c81c8052484a;name=VCM;type=folder;parent=0b06c81c8052483a;|id=0c06c81c80269e63;name=Invoices;type=cabinet;|id=0b06c81c8026a008;name=other;type=folder;parent=0c06c81c80269e63;|id=0b06c81c8027a600;name=Workflow;type=folder;parent=0b06c81c8026a008;|id=0b06c81c8027a601;name=Worksheet;type=folder;parent=0b06c81c8027a600;|id=0c06c81c8051c7d3;name=Receipts;type=cabinet;|id=0b06c81c80545f32;name=VR_2;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f33;name=VR_3;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f30;name=VR_1;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c8053486d;name=VR;type=folder;parent=0c06c81c8051c7d3;|id=0b06c81c80545f31;name=test2;type=folder;parent=0b06c81c8053486d;|id=0c06c81c8051c7d2;name=Source;type=root;|id=0b06c81c80524a8b;name=gem;type=folder;parent=0c06c81c8051c7d2;|id=0b06c81c80521681;name=Code;type=folder;parent=0b06c81c80524a8b;|id=0b06c81c8051cba7;name=pfm;type=folder;parent=0b06c81c80524a8b;";
System.out.println("Temp folder : " + System.getProperty(JAVA_IO_TMPDIR));
List<FolderObj> folders = MenuHelper.parseResponseString(FOLDER_STRUCTURE);
if(folders != null) {
List<MegaMenuDTO> menuDTOList = MenuHelper.prepareMenu(folders);
List<File> rootDirs = new ArrayList<>();
File rootDir = new File(System.getProperty(JAVA_IO_TMPDIR) + SEPARATOR + TEMP_ROOT_FOLDER);
//Check and Delete the root folder, if present, before processing.
if(rootDir.exists()) {
rootDirs.add(rootDir);
for(File file : rootDirs) {
recursivelyDelete(file);
}
}
//Create a fresh root dir.
rootDirs.clear();
rootDir = createTempRootDir(TEMP_ROOT_FOLDER);
rootDirs.add(rootDir);
//System.out.println("Tree : " + menuDTOList);
for(MegaMenuDTO mmd: menuDTOList){
printMenu(mmd, "\t");
captureIdNameMap(mmd);
printPaths(mmd, TEMP_ROOT_FOLDER + SEPARATOR + mmd.getName());
}
for (Map.Entry<String, List<MegaMenuDTO>> entry : parentChildMap.entrySet()) {
String key = entry.getKey();
List<MegaMenuDTO> value = entry.getValue();
for(MegaMenuDTO dto : value) {
if(idNameMap.get(key) == null) {
System.out.println("Children of " + key + " -> " + dto.getName() + ", ID: " + dto.getId());
} else {
System.out.println("Children of " + idNameMap.get(key) + " -> " + dto.getName() + ", ID: " + dto.getId());
}
}
}
System.out.println("--------------------------------------\n");
for (Map.Entry<String, List<MegaMenuDTO>> entry : parentChildMap.entrySet()) {
String key = entry.getKey();
List<MegaMenuDTO> value = entry.getValue();
if(key.equals("ROOT")) {
for(MegaMenuDTO dto : value) {
System.out.println("Root Folder is : " + dto.getName());
//createTempRootDir(TEMP_ROOT_FOLDER + SEPARATOR + dto.getName());
System.out.println(TEMP_ROOT_FOLDER + SEPARATOR + dto.getName());
printFoldersRecursively(parentChildMap.get(dto.getId()), TEMP_ROOT_FOLDER + SEPARATOR + dto.getName());
}
}
}
}
}
public static void printFoldersRecursively(List<MegaMenuDTO> value, String rootPath) throws IOException {
for (MegaMenuDTO inDTO1 : value) {
System.out.println(rootPath + SEPARATOR + inDTO1.getName());
for(MegaMenuDTO childItem : inDTO1.getChildrenItems()) {
System.out.println(rootPath + SEPARATOR + inDTO1.getName() + SEPARATOR + childItem.getName());
printFoldersRecursively(childItem.getChildrenItems(), rootPath + SEPARATOR + inDTO1.getName() + SEPARATOR + childItem.getName());
}
}
}
public static List<FolderObj> parseResponseString(final String input) {
if(input == null) {
return null;
}
List<FolderObj> menuList = new ArrayList<>();
String[] parsedValues = input.split(RECORD_ELEMENT_DELIM);
for(short i=0; i < parsedValues.length; i++) {
menuList.add(digest(filterValue(parsedValues[i])));
}
return menuList;
}
public static String filterValue(String input) {
if(input == null) {
return input;
}
if(input.contains(FOLDERTREE_STR)) {
input = input.substring(input.indexOf(FOLDERTREE_STR) + FOLDERTREE_STR.length());
}
return input;
}
public static FolderObj digest(String input) {
if(input == null) {
return null;
}
Map<String, String> holder = new HashMap<>();
String [] keyVals = input.split(";");
for(String keyVal : keyVals) {
String [] parts = keyVal.split("=");
holder.put(parts[0], parts[1]);
}
FolderObj folderObj = null;
String childId = null;
String name = null;
String type = null;
String parentId = null;
for(Map.Entry<String, String> entry : holder.entrySet()) {
String key = entry.getKey();
if(key.equals("id")) {
childId = entry.getValue();
} else if(key.equals("name")) {
name = entry.getValue();
} else if(key.equals("type")) {
type = entry.getValue();
} else if(key.equals("parent")) {
parentId = entry.getValue();
}
folderObj = new FolderObj(childId, parentId, name, type);
}
return folderObj;
}
public static List<MegaMenuDTO> prepareMenu(List<FolderObj> folderList) {
// Arrange String corresponds to the Id
Map<String, MegaMenuDTO> megaMenuMap = new HashMap<>();
// populate a Map
for(FolderObj folderObj: folderList){
MegaMenuDTO mmdChild;
if(megaMenuMap.containsKey(folderObj.getChildId())){
mmdChild = megaMenuMap.get(folderObj.getChildId());
} else{
mmdChild = new MegaMenuDTO();
megaMenuMap.put(folderObj.getChildId(),mmdChild);
}
mmdChild.setId(folderObj.getChildId());
mmdChild.setParentId(folderObj.getParentId());
mmdChild.setName(folderObj.getName());
mmdChild.setType(folderObj.getType());
// ------ Parent ----
MegaMenuDTO mmdParent;
if(megaMenuMap.containsKey(folderObj.getParentId())){
mmdParent = megaMenuMap.get(folderObj.getParentId());
} else{
mmdParent = new MegaMenuDTO();
megaMenuMap.put(folderObj.getParentId(),mmdParent);
}
mmdParent.setId(folderObj.getParentId());
mmdParent.addChildrenItem(mmdChild);
}
// Get the root
List<MegaMenuDTO> menuList = new ArrayList<MegaMenuDTO>();
for(MegaMenuDTO megaMenuDTO : megaMenuMap.values()){
if(megaMenuDTO.getParentId() == null)
menuList.add(megaMenuDTO);
}
return menuList;
}
private static void printMenu(MegaMenuDTO dto, String tabValue) {
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
System.out.println(tabValue + childDTO.getName());
tabValue = "\t" + tabValue;
printMenu(childDTO, tabValue);
}
}
private static void captureIdNameMap(MegaMenuDTO dto) throws IOException {
idNameMap.put(dto.getId(), dto.getName());
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
idNameMap.put(childDTO.getId(), childDTO.getName());
captureIdNameMap(childDTO);
}
}
private static void printPaths(MegaMenuDTO dto, String name) throws IOException {
if(dto.getParentId() == null) {
if(parentChildMap.get("ROOT") == null) {
List<MegaMenuDTO> parentList = new ArrayList<MegaMenuDTO>();
parentList.add(dto);
parentChildMap.put("ROOT", parentList);
} else {
List<MegaMenuDTO> parentList = parentChildMap.get("ROOT");
parentList.add(dto);
parentChildMap.put("ROOT", parentList);
}
}
for(MegaMenuDTO childDTO : dto.getChildrenItems()) {
if (parentChildMap.get(childDTO.getParentId()) == null) {
List<MegaMenuDTO> parentList = new ArrayList<MegaMenuDTO>();
parentList.add(childDTO);
parentChildMap.put(childDTO.getParentId(), parentList);
} else {
List<MegaMenuDTO> parentList = parentChildMap.get(childDTO.getParentId());
parentList.add(childDTO);
parentChildMap.put(childDTO.getParentId(), parentList);
}
System.out.println(name + SEPARATOR + childDTO.getName() + ", ParentId : " + childDTO.getParentId());
createTempRootDir(name + SEPARATOR + childDTO.getName());
name = name + SEPARATOR + childDTO.getName();
printPaths(childDTO, name);
}
}
public static File createTempRootDir(String name) throws IOException {
final File sysTempDir = new File(System.getProperty(JAVA_IO_TMPDIR));
File newTempDir = new File(sysTempDir, name);
if (newTempDir.mkdirs()) {
return newTempDir;
} else {
throw new IOException("Failed to create temp dir named " + newTempDir.getAbsolutePath());
}
}
/**
* Recursively delete file or directory
*
* #param fileOrDir
* the file or dir to delete
* #return true iff all files are successfully deleted
*/
public static void recursivelyDelete(File fileOrDir) throws IOException {
Path directory = Paths.get(fileOrDir.getAbsolutePath());
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
}
I am trying to convert json string in java bean using Gson but it is returnig null value.
public static void convert(String args) {
String json =
"{"body":{"response":{"total":"294","num":"294","filelist":[{"id":"56712","camname":"Camera1","camid":"514","start":"2016-07-08 12:00:38","end":"2016-07-08 12:03:00","stream":"3","recReason":"Activity","filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.jpg","nvrip":"192.168.0.200:8095"},{"id":"56708","camname":"Camera1","camid":"514","start":"2016-07-08 11:58:14","end":"2016-07-08 12:00:36","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.jpg","nvrip":"192.168.0.200:8095"},{"id":"56705","camname":"Camera1","camid":"514","start":"2016-07-08 11:55:49","end":"2016-07-08 11:58:11","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.jpg","nvrip":"192.168.0.200:8095"},{"id":"56702","camname":"Camera1","camid":"514","start":"2016-07-08 11:53:25","end":"2016-07-08 11:55:47","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.mrv","snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.jpg","nvrip":"192.168.0.200:8095"},{"id":"56699","camname":"Camera1","camid":"514","start":"2016-07-08 11:51:00","end":"2016-07-08 11:53:22","stream":"3","recReason":"Activity","filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.mrv","snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.jpg","nvrip":"192.168.0.200:8095"}],"status":"OK"}}}";
// Now do the magic.
RecordingListResponseDTO data = new Gson().fromJson(json, RecordingListResponseDTO .class);
// Show it.
System.out.println("converted data :"+data);
}
My Bean Class is following.
RecordingListResponseDTO
public class RecordingListResponseDTO implements Serializable {
private String status;
private int total;
private int num;
List<FileListDTO> fileList;
public RecordingListResponseDTO(){
}
public RecordingListResponseDTO(String status, int total, int num, List<FileListDTO> fileList) {
this.status = status;
this.total = total;
this.num = num;
this.fileList = fileList;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public List<FileListDTO> getFileList() {
return fileList;
}
public void setFileList(List<FileListDTO> fileList) {
this.fileList = fileList;
}
#Override
public String toString() {
return "RecordingListResponseDTO{" +
"status='" + status + '\'' +
", total=" + total +
", num=" + num +
", fileList=" + fileList +
'}';
}}
FileListDTO.java
public class FileListDTO {
private int id;
private String camname;
private int camid;
private Date start;
private Date end;
private int stream;
private String recReason;
private String filename;
private String snapshot;
private String nvrip;
public FileListDTO(int id, String camname, Date start, int camid, Date end, int stream, String recReason, String filename, String snapshot, String nvrip) {
this.id = id;
this.camname = camname;
this.start = start;
this.camid = camid;
this.end = end;
this.stream = stream;
this.recReason = recReason;
this.filename = filename;
this.snapshot = snapshot;
this.nvrip = nvrip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCamname() {
return camname;
}
public void setCamname(String camname) {
this.camname = camname;
}
public int getCamid() {
return camid;
}
public void setCamid(int camid) {
this.camid = camid;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public int getStream() {
return stream;
}
public void setStream(int stream) {
this.stream = stream;
}
public String getRecReason() {
return recReason;
}
public void setRecReason(String recReason) {
this.recReason = recReason;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getSnapshot() {
return snapshot;
}
public void setSnapshot(String snapshot) {
this.snapshot = snapshot;
}
public String getNvrip() {
return nvrip;
}
public void setNvrip(String nvrip) {
this.nvrip = nvrip;
}
#Override
public String toString() {
return "FileListDTO{" +
"id=" + id +
", camname='" + camname + '\'' +
", camid=" + camid +
", start=" + start +
", end=" + end +
", stream=" + stream +
", recReason='" + recReason + '\'' +
", filename='" + filename + '\'' +
", snapshot='" + snapshot + '\'' +
", nvrip='" + nvrip + '\'' +
'}';
}}
I am getting null value after converting Json string to Java object.
what I am doing wrong please suggest me.
Thank in advance.
Prerequisites:
Following JSON has been used:
{
"body":{
"response":{
"total":294,
"num":294,
"filelist":[
{
"id":56712,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 12:00:38",
"end":"2016-07-08 12:03:00",
"stream":3,
"recReason":"Activity",
"filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56708,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:58:14",
"end":"2016-07-08 12:00:36",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56705,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:55:49",
"end":"2016-07-08 11:58:11",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.mrv",
"snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56702,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:53:25",
"end":"2016-07-08 11:55:47",
"stream":3,
"recReason":"Activity",
"filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.mrv",
"snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.jpg",
"nvrip":"192.168.0.200:8095"
},
{
"id":56699,
"camname":"Camera1",
"camid":514,
"start":"2016-07-08 11:51:00",
"end":"2016-07-08 11:53:22",
"stream":3,
"recReason":"Activity",
"filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.mrv",
"snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.jpg",
"nvrip":"192.168.0.200:8095"
}
],
"status":"OK"
}
}
}
Step 1:
Modify the declaration of private List<FileListDTO> fileList in RecordingListResponseDTO.java as follows:
#SerializedName("filelist")
private List<FileListDTO> fileList
Step 2:
Define following class MyDateTypeAdapter.java:
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class MyDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private DateFormat dateFormat;
public MyDateTypeAdapter() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
#Override
public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateFormat.format(date));
}
#Override
public synchronized Date deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) {
try {
return dateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
Step 3:
Modify the method convert(String args) as follows:
public static void convert(String args) {
JsonParser parser = new JsonParser();
String json = parser.parse(args)
.getAsJsonObject()
.getAsJsonObject("body")
.getAsJsonObject("response")
.toString();
// Now do the magic.
RecordingListResponseDTO data = new GsonBuilder()
.registerTypeAdapter(Date.class, new MyDateTypeAdapter())
.create().fromJson(json, RecordingListResponseDTO.class);
// Show it.
System.out.println("converted data :"+data);
}
For testing purpose, you may try storing the JSON in a file i.e. D:/test.json and call the method by:
String json = new String(Files.readAllBytes(Paths.get("D:/test.json")));
convert(json);
something you need to change the models class like,
Initially in your json response data contains "body" tag that's represents to object, initially you need to create the class for object tag,then all data contains inside your "body" tag, so parse all data inside from body data,
may help this code,
public class RecordingListResponseDTO implements Serializable {
Recordinglist body;
public class Recordinglist(){
Recordresponse response;
public class Recordresponse(){
String total;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
}
}
I am convert a json data into POJO with array of objects using Codehaus Jackson.
I am having problems with the array of objects. I am getting errors like "Can not deserialize instance ... out of START_ARRAY token".
Below are my codes
JSON Data (flightItineraryPrice.json)
{
"tripType": "OneWay",
"tripInfos":[
{
"from":"EARTH",
"to":"MOON",
"fromSchedule":"2015-12-21T04:30:00",
"toSchedule":"2015-12-21T06:50:00"
},
{
"from":"MOON",
"to":"MARS",
"fromSchedule":"2015-12-21T03:30:00",
"toSchedule":"2015-12-21T011:10:00"
},
{
"from":"VENUS",
"to":"KEPLER",
"fromSchedule":"2015-12-21T01:30:00",
"toSchedule":"2015-12-21T22:30:00"
},
{
"from":"EARTH",
"to":"SUN",
"fromSchedule":"2015-12-20T02:30:00",
"toSchedule":"2015-12-29T15:10:00"
}
],
"adultFare":{
"paxType":"ADT",
"baseFare":"1000",
"totalFeesAndTaxes":"300",
"totalAmount":"1300.00"
},
"childFare":{
"paxType":"CHD",
"baseFare":"750",
"totalFeesAndTaxes":"250",
"totalAmount":"1000.00"
},
"infantFare":{
"paxType":"INF",
"baseFare":"250",
"totalFeesAndTaxes":"25",
"totalAmount":"275.00"
},
"adultCount":"1",
"childCount":"1",
"infantCount":"2"
}
Class (JacksonFlightItineraryPrice.java)
package com.jgtt.samples;
import java.util.*;
import org.codehaus.jackson.annotate.JsonProperty;
public class JacksonFlightItineraryPrice {
private String tripType;
#JsonProperty("tripInfos")
private JacksonFlightItineraryPrice.TripInfo tripInfos;
private JacksonFlightItineraryPrice.PaxFare adultFare;
private JacksonFlightItineraryPrice.PaxFare childFare;
private JacksonFlightItineraryPrice.PaxFare infantFare;
private short adultCount;
private short childCount;
private short infantCount;
public JacksonFlightItineraryPrice() {}
public String getTripType() {
return (this.tripType);
}
public void setTripType(String tripType) {
this.tripType = tripType;
}
public JacksonFlightItineraryPrice.TripInfo getTripInfos() {
return (this.tripInfos);
}
public void setTripInfos(JacksonFlightItineraryPrice.TripInfo tripInfos) {
this.tripInfos = tripInfos;
}
public JacksonFlightItineraryPrice.PaxFare getAdultFare() {
return (this.adultFare);
}
public void setAdultFare(JacksonFlightItineraryPrice.PaxFare adultFare) {
this.adultFare = adultFare;
}
public JacksonFlightItineraryPrice.PaxFare getChildFare() {
return (this.childFare);
}
public void setChildFare(JacksonFlightItineraryPrice.PaxFare childFare) {
this.childFare = childFare;
}
public JacksonFlightItineraryPrice.PaxFare getInfantFare() {
return (this.infantFare);
}
public void setInfantFare(JacksonFlightItineraryPrice.PaxFare infantFare) {
this.infantFare = infantFare;
}
public short getAdultCount() {
return (this.adultCount);
}
public void setAdultCount(short adultCount) {
this.adultCount = adultCount;
}
public short getChildCount() {
return (this.childCount);
}
public void setChildCount(short childCount) {
this.childCount = childCount;
}
public short getInfantCount() {
return (this.infantCount);
}
public void setInfantCount(short infantCount) {
this.infantCount = infantCount;
}
public static class TripInfo {
private List<JacksonFlightItineraryPrice.FlightInfoParameter> flightInfoParameters;
public List getFlightInfoParameters() {
return (this.flightInfoParameters);
}
public void setFlightInfoParameters(List flightInfoParameters) {
this.flightInfoParameters = flightInfoParameters;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[\n");
if(null != flightInfoParameters){
sb.append(" flightInfoParameters:\n");
boolean isFirst = true;
for(FlightInfoParameter f : flightInfoParameters){
if(!isFirst){
sb.append(",\n");
}
sb.append(f);
isFirst = false;
}
sb.append("\n");
}
else {
sb.append(" flightInfoParameters=null\n");
}
sb.append("]");
return sb.toString();
}
}
public static class FlightInfoParameter {
private String from;
private String to;
private String fromSchedule;
private String toSchedule;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getFromSchedule() {
return fromSchedule;
}
public void setFromSchedule(String fromSchedule) {
this.fromSchedule = fromSchedule;
}
public String getToSchedule() {
return toSchedule;
}
public void setToSchedule(String toSchedule) {
this.toSchedule = toSchedule;
}
#Override
public String toString() {
return "User [ "+from+"(" + fromSchedule + ") -> " + to + "(" + toSchedule + ") ]";
}
}
public static class PaxFare {
private String paxType;
private Double baseFare;
private Double totalFeesAndTaxes;
private Double totalAmount;
public String getPaxType() {
return paxType;
}
public void setPaxType(String paxType) {
this.paxType = paxType;
}
public Double getBaseFare() {
return baseFare;
}
public void setBaseFare(Double baseFare) {
this.baseFare = baseFare;
}
public Double getTotalFeesAndTaxes() {
return totalFeesAndTaxes;
}
public void setTotalFeesAndTaxes(Double totalFeesAndTaxes) {
this.totalFeesAndTaxes = totalFeesAndTaxes;
}
public Double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(Double totalAmount) {
this.totalAmount = totalAmount;
}
#Override
public String toString() {
return "User [paxType=" + paxType + ", baseFare=" + baseFare + ", totalFeesAndTaxes" + totalFeesAndTaxes + ", totalAmount=" + totalAmount + "]";
}
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[\n");
sb.append(" tripType=" + tripType + ",\n");
sb.append(" tripInfos=" + tripInfos + ",\n");
sb.append(" adultFare=" + adultFare + ",\n");
sb.append(" childFare=" + childFare + ",\n");
sb.append(" infantFare=" + infantFare + ",\n");
sb.append(" adultCount=" + adultCount + ",\n");
sb.append(" childCount=" + childCount + ",\n");
sb.append(" infantCount=" + infantCount + "\n]");
return sb.toString();
}
}
Main Application (JacksonExample.java)
package com.jgtt.samples;
import java.util.*;
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.TypeReference;
import org.codehaus.jackson.map.type.CollectionType;
import org.codehaus.jackson.map.type.TypeFactory;
public class JacksonExample {
private static void flightJsonToPojo(){
ObjectMapper mapper = new ObjectMapper();
try {
String file_url = "d:\\Work files\\Java Test Codes\\Jackson\\flightItineraryPrice.json";
File jsonFile = new File(file_url);
JacksonFlightItineraryPrice flightInfo = mapper.readValue(jsonFile, JacksonFlightItineraryPrice.class);
System.out.println(flightInfo);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
flightJsonToPojo();
}
}
The only part in the json data that I am having problem with is the "tripInfos" because its value is an arraylist of objects. If I remove tripInfos... everything works fine... but I really needed it also.
Hope somebody can show me the way :)
The class JacksonFlightItineraryPrice has one attribute tripInfos that isn't an array:
#JsonProperty("tripInfos")
private JacksonFlightItineraryPrice.TripInfo tripInfos;
and TripInfo has flightInfoParameters as a List of List<JacksonFlightItineraryPrice.FlightInfoParameter>
But in your json tripInfos is an array of JacksonFlightItineraryPrice.FlightInfoParameter.
Instead it should be:
{
"tripType": "OneWay",
"tripInfos": {
"flightInfoParameters" : [
{
"from":"EARTH",
"to":"MOON",
"fromSchedule":"2015-12-21T04:30:00",
"toSchedule":"2015-12-21T06:50:00"
},
{
"from":"MOON",
"to":"MARS",
"fromSchedule":"2015-12-21T03:30:00",
"toSchedule":"2015-12-21T011:10:00"
},
{
"from":"VENUS",
"to":"KEPLER",
"fromSchedule":"2015-12-21T01:30:00",
"toSchedule":"2015-12-21T22:30:00"
},
{
"from":"EARTH",
"to":"SUN",
"fromSchedule":"2015-12-20T02:30:00",
"toSchedule":"2015-12-29T15:10:00"
}
]
},
"adultFare":{
"paxType":"ADT",
"baseFare":"1000",
"totalFeesAndTaxes":"300",
"totalAmount":"1300.00"
},
"childFare":{
"paxType":"CHD",
"baseFare":"750",
"totalFeesAndTaxes":"250",
"totalAmount":"1000.00"
},
"infantFare":{
"paxType":"INF",
"baseFare":"250",
"totalFeesAndTaxes":"25",
"totalAmount":"275.00"
},
"adultCount":"1",
"childCount":"1",
"infantCount":"2"
}
or if you cannot change the JSON, then in JacksonFlightItineraryPrice the property tripInfos should be a list of FlightInfoParameter :
#JsonProperty("tripInfos")
private List<JacksonFlightItineraryPrice.FlightInfoParameter> tripInfos;