Created
September 10, 2017 09:03
-
-
Save ariesmcrae/4a0d4a94ae88b9b17468304339f2ca1c to your computer and use it in GitHub Desktop.
Java POJO to JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.core.JsonProcessingException; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import lombok.Getter; | |
import java.util.ArrayList; | |
import java.util.List; | |
@Getter | |
public class CsvError { | |
private String filename; | |
private List<Error> errors = new ArrayList<>(); | |
public void addError(Error error) { | |
errors.add(error); | |
} | |
public void setFilename(String filename) { | |
this.filename = filename; | |
} | |
@Getter | |
public static class Error { | |
private long lineNumber; | |
private String errorMessage; | |
public static String INCORRECT_NO_COLUMNS = "Incorrect number of columns."; | |
public Error(long lineNumber) { | |
this(lineNumber, INCORRECT_NO_COLUMNS); | |
} | |
public Error(long lineNumber, String errorMessage) { | |
this.lineNumber = lineNumber; | |
this.errorMessage = errorMessage; | |
} | |
} | |
public static void main(String[] args) throws JsonProcessingException { | |
CsvError container = new CsvError(); | |
container.setFilename("abc.csv"); | |
Error error1 = new Error(3); | |
Error error2 = new Error(7); | |
container.addError(error1); | |
container.addError(error2); | |
String serializedJson = new ObjectMapper().writeValueAsString(container); | |
System.out.println(serializedJson); | |
} | |
} | |
/** Output | |
{ | |
"filename":"aaaa.txt", | |
"errors":[ | |
{ | |
"lineNumber":3, | |
"errorMessage":"Incorrect number of columns" | |
}, | |
{ | |
"lineNumber":7, | |
"errorMessage":"Incorrect number of columns" | |
} | |
] | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment