Catching JSONException - java

I'm getting a JSON Exception in this code:
JSONObject jObject = new JSONObject(JSONString);
pontosUsuario.setIdUsuario(jObject.getInt("idUsuario"));
//Toast.makeText(this, pontosUsuario.idUsuario, Toast.LENGTH_LONG).show();
pontosUsuario.setNomeUsuario(jObject.getString("nomeUsuario"));
pontosUsuario.setCPF(jObject.getString("CPF"));
pontosUsuario.setEmail(jObject.getString("email"));
pontosUsuario.setSigla(jObject.getString("sigla"));
pontosUsuario.setSenha(jObject.getString("senha"));
pontosUsuario.setInstuicao(jObject.getString("instituicao"));
JSONArray jArr = new JSONArray(jObject.getString("listaDePontos"));
for (int i = 0; i < jArr.length(); i++) {
JSONObject temp = jArr.getJSONObject(i);
Ponto ponto = new Ponto();
ponto.setIdPonto(temp.getString("idPonto"));
ponto.setPontoNome(temp.getString("pontoNome"));
String data = temp.getString("dtCampo");
data = data.substring(0, 10);
//dtCampo = temp.getString("dtCampo");
try {
ponto.setDtCampo(new SimpleDateFormat(data, Locale.ENGLISH).parse(data));
} catch (ParseException e) {
e.printStackTrace();
}
ponto.setProjeto(temp.getInt("projeto"));
ponto.setUTMEste(temp.getDouble("UTMEste"));
ponto.setUTMNorte(temp.getDouble("UTMNorte"));
ponto.setUTMFuso(temp.getInt("UTMFuso"));
ponto.setUTMHemisferio(temp.getString("UTMHemisferio"));
ponto.setLatDec(temp.getDouble("latDec"));
ponto.setLongDec(temp.getDouble("longDec"));
ponto.setAltitude(temp.getInt("altitude"));
ponto.setDescPonto(temp.getString("descPonto"));
ponto.setComplement(temp.getString("complement"));
//ponto.getAnaliseCampo();
AnaliseCampo analiseCampo = new AnaliseCampo();
//JSONObject anObj = jObject.getJSONObject("analiseCampo");
JSONObject anObj = jObject.getJSONObject("analiseCampo");
//AnaliseCampo analiseCampo = new AnaliseCampo();
analiseCampo.setNomeEstrutura(anObj.getString("nomeEstrutura"));
analiseCampo.setIdAnCampo(anObj.getString("idAnCampo"));
analiseCampo.setDescEstrutura(anObj.getString("descEstrutura"));
analiseCampo.setEhBrunton(anObj.getBoolean("ehBrunton"));
ponto.setAnaliseCampo(analiseCampo);
//ponto.setAnaliseCampo(temp.get("analiseCampo");
The Exception is: detailMessage "No value for analiseCampo" (id=830007838576)
Here is the Ponto.class:
public class Ponto {
private String idPonto;
private String pontoNome;
private Date dtCampo;
private int projeto;
private double UTMEste;
private double UTMNorte;
private int UTMFuso;
private String UTMHemisferio;
private double latDec;
private double longDec;
private int altitude;
private String descPonto;
private String complement;
private AnaliseCampo analiseCampo;
private ArrayList<Arquivo> arquivos;
private ArrayList<PontoUnGeologica> idUnidadeGeologica;
public String getIdPonto() {
return idPonto;
}
public void setIdPonto(String idPonto) {
this.idPonto = idPonto;
}
public String getPontoNome() {
return pontoNome;
}
public void setPontoNome(String pontoNome) {
this.pontoNome = pontoNome;
}
public Date getDtCampo() {
return dtCampo;
}
public void setDtCampo(Date dtCampo) {
this.dtCampo = dtCampo;
}
public int getProjeto() {
return projeto;
}
public void setProjeto(int projeto) {
this.projeto = projeto;
}
public double getUTMEste() {
return UTMEste;
}
public void setUTMEste(double uTMEste) {
UTMEste = uTMEste;
}
public double getUTMNorte() {
return UTMNorte;
}
public void setUTMNorte(double uTMNorte) {
UTMNorte = uTMNorte;
}
public int getUTMFuso() {
return UTMFuso;
}
public void setUTMFuso(int uTMFuso) {
UTMFuso = uTMFuso;
}
public String getUTMHemisferio() {
return UTMHemisferio;
}
public void setUTMHemisferio(String utmHemisferio) {
UTMHemisferio = utmHemisferio;
}
public double getLatDec() {
return latDec;
}
public void setLatDec(double latDec) {
this.latDec = latDec;
}
public double getLongDec() {
return longDec;
}
public void setLongDec(double longDec) {
this.longDec = longDec;
}
public int getAltitude() {
return altitude;
}
public void setAltitude(int altitude) {
this.altitude = altitude;
}
public String getDescPonto() {
return descPonto;
}
public void setDescPonto(String descPonto) {
this.descPonto = descPonto;
}
public String getComplement() {
return complement;
}
public void setComplement(String complement) {
this.complement = complement;
}
public AnaliseCampo getAnaliseCampo() {
return analiseCampo;
}
public void setAnaliseCampo(AnaliseCampo analiseCampo) {
this.analiseCampo = analiseCampo;
}
public ArrayList<Arquivo> getArquivos() {
return arquivos;
}
public void setArquivos(ArrayList<Arquivo> arquivos) {
this.arquivos = arquivos;
}
public ArrayList<PontoUnGeologica> getIdUnigadeGeologica() {
return idUnidadeGeologica;
}
public void setIdUnigadeGeologica(ArrayList<PontoUnGeologica> idUnigadeGeologica) {
this.idUnidadeGeologica = idUnigadeGeologica;
}
public Ponto()
{
arquivos = new ArrayList<Arquivo>();
idUnidadeGeologica = new ArrayList<PontoUnGeologica>();
analiseCampo = new AnaliseCampo();
}
}
And this is the AnaliseCampo.class
public class AnaliseCampo {
public String nomeEstrutura;
public String idAnCampo;
public String descEstrutura;
public boolean ehBrunton;
public ArrayList<AnaliseEstrutural> analiseEstruturais;
public String getNomeEstrutura() {
return nomeEstrutura;
}
public void setNomeEstrutura(String nomeEstrutura) {
this.nomeEstrutura = nomeEstrutura;
}
public String getIdAnCampo() {
return idAnCampo;
}
public void setIdAnCampo(String idAnCampo) {
this.idAnCampo = idAnCampo;
}
public String getDescEstrutura() {
return descEstrutura;
}
public void setDescEstrutura(String descEstrutura) {
this.descEstrutura = descEstrutura;
}
public boolean isEhBrunton() {
return ehBrunton;
}
public void setEhBrunton(boolean ehBrunton) {
this.ehBrunton = ehBrunton;
}
public ArrayList<AnaliseEstrutural> getAnaliseEstruturais() {
return analiseEstruturais;
}
public void setAnaliseEstruturais(
ArrayList<AnaliseEstrutural> analiseEstruturais) {
this.analiseEstruturais = analiseEstruturais;
}
public AnaliseCampo()
{
analiseEstruturais = new ArrayList<AnaliseEstrutural>();
}
}
Here is the JSON:
"idUsuario": 20,
"nomeUsuario": "Barbara Trzaskos",
"CPF": "978824029-15",
"email": "barbaratrzaskos#ufpr.br",
"sigla": "BTR",
"senha": "safira",
"instuicao": "Universidade Federal do Paraná",
"listaDePontos": [
{
"idPonto": "BTR0001",
"pontoNome": "BTR-0001",
"dtCampo": "2011-04-29T00:00:00",
"projeto": 2,
"UTMEste": 547276.0,
"UTMNorte": 7285137.0,
"UTMFuso": 22,
"UTMHemisferio": "S",
"latDec": -24.5469,
"longDec": -50.5332,
"altitude": 0,
"descPonto": "Arenito mal selecionado. Apresenta fina banda de deformação, como um suave ressalto no relevo e coloração mais clara. Exibe plano subvertical com padrão anastomosado e cinemática aparente sinistral",
"complement": "Coleta de amostra orientada.",
"analiseCampo": {
"nomeEstrutura": "-",
"idAnCampo": "BTR0001",
"descEstrutura": "",
"ehBrunton": true,
"analiseEstruturais": [
{
"idEstrutura": "BTR0001001",
"ordem": 0,
"tipo": "Plano",
"codigo": "F",
"brunton": "N42W/86SW",
"clar": "228/86",
"azimute": "228",
"direcao": "42",
"quadrante": "SW",
"sentido": "Sinistral",
"descricao": "",
"mergulho": "86",
"familia": ""
}
]
},
"arquivos": [],
"idUnigadeGeologica": [
{
"idUnidade": 816
},
{
"idUnidade": 2295
}
]
}
]

You are accessing the wrong JSON object in this line:
JSONObject anObj = jObject.getJSONObject("analiseCampo");
It should be:
JSONObject anObj = temp.getJSONObject("analiseCampo");
Since temp is what you are assigning each element of the listaDePontos array to. On a side note, given the complexity of your data, you should consider mapping the JSON directly to your object using:
String json = "" ; // <-- your JSON here
Ponto ponto = new Gson().fromJson(json, Ponto.class);

Related

creating an excel sheet data after joining 4 table into excel using spring boot and poi

I want to create an excel on hitting an spring boot rest Api. I used used POI jar for creating excel but always receive below response "{
"timestamp": "2020-11-25T10:10:16.723+00:00",
"message": "query did not return a unique result: 2; nested exception is javax.persistence.NonUniqueResultException: query did not return a unique result: 2",
"status": 500
}please assist I am a bigneer
"
// Exceel helper class
public class ExcelHelper {
public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
static String[] HEADERs = {
"studentRollNo",
"studentFullName",
"studentFatherName",
"studentMotherName",
"studentDob",
"studentGender",
"studentEmail",
"studentContactNo",
"studentAddress",
"studentZipCode",
"studentState",
"studentCity",
"studentEducationId",
"studentEducationSscMarks",
"studentEducationSscPassYear",
"studentEducationHsscMarks",
"studentEducationHsscStream",
"studentEducationHsscPasYear",
"studentEducationGradCourse",
"studentEducationGradsCgpa",
"studentEducationGradPassYear",
"studentEducationPgCourse",
"studentEducationPgCgpa",
"studentEducationPgPassYear",
"studentEducationYear",
"studentEducationGapReason",
"studentcertificationId",
"studentcertificationOrgiDetails",
"studentCertificationTitle",
"studentcertificationIssueDate"
};
public static ByteArrayInputStream tutorialsToExcel(List<ExcelPojo> student ) {
try (Workbook workbook = new XSSFWorkbook();
ByteArrayOutputStream out = new ByteArrayOutputStream();)
{
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet();
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(IndexedColors.BLUE.getIndex());
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Row for Header
Row headerRow = sheet.createRow(0);
// Header
for (int col = 0; col < HEADERs.length; col++) {
Cell cell = headerRow.createCell(col);
cell.setCellValue(HEADERs[col]);
cell.setCellStyle(headerCellStyle);
}
// CellStyle for Age
CellStyle ageCellStyle = workbook.createCellStyle();
ageCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("#"));
int rowIdx = 1;
for (ExcelPojo tutorial : student) {
Row row = sheet.createRow(rowIdx++);
row.createCell(0).setCellValue(tutorial.getStudentRollNo());
row.createCell(1).setCellValue(tutorial.getStudentFullName());
row.createCell(2).setCellValue(tutorial.getStudentFatherName());
row.createCell(3).setCellValue(tutorial.getStudentMotherName());
row.createCell(4).setCellValue(tutorial.getStudentDob());
row.createCell(5).setCellValue(tutorial.getStudentGender());
row.createCell(6).setCellValue(tutorial.getStudentEmail());
row.createCell(7).setCellValue(tutorial.getStudentContactNo());
row.createCell(8).setCellValue(tutorial.getStudentAddress());
row.createCell(9).setCellValue(tutorial.getStudentZipCode());
row.createCell(10).setCellValue(tutorial.getStudentState());
row.createCell(11).setCellValue(tutorial.getStudentCcity());
row.createCell(12).setCellValue(tutorial.getStudentEducationId());
row.createCell(13).setCellValue(tutorial.getStudentEducationSscMarks());
row.createCell(14).setCellValue(tutorial.getStudentEducationSscPassYear());
row.createCell(15).setCellValue(tutorial.getStudentEducationHsscMarks());
row.createCell(16).setCellValue(tutorial.getStudentEducationHsscStream());
row.createCell(17).setCellValue(tutorial.getStudentEducationHsscPasYear());
row.createCell(18).setCellValue(tutorial.getStudentEducationGradCourse());
row.createCell(19).setCellValue(tutorial.getStudentEducationGradsCgpa());
row.createCell(20).setCellValue(tutorial.getStudentEducationGradPassYear());
row.createCell(21).setCellValue(tutorial.getStudentEducationPgCourse());
row.createCell(22).setCellValue(tutorial.getStudentEducationPgCgpa());
row.createCell(23).setCellValue(tutorial.getStudentEducationPgPassYear());
row.createCell(24).setCellValue(tutorial.getStudentEducationYear());
row.createCell(25).setCellValue(tutorial.getStudentEducationGapReason());
row.createCell(26).setCellValue(tutorial.getStudentcertificationId());
row.createCell(27).setCellValue(tutorial.getStudentcertificationOrgiDetails());
row.createCell(28).setCellValue(tutorial.getStudentcertificationTitle());
row.createCell(29).setCellValue(tutorial.getStudentcertificationIssueDate());
}
workbook.write(out);
return new ByteArrayInputStream(out.toByteArray());
} catch (IOException e) {
throw new RuntimeException("fail to import data to Excel file: " + e.getMessage());
}
}
}
// POJO
public class ExcelPojo {
private String studentRollNo;
private String studentFullName;
private String studentFatherName;
private String studentMotherName;
private String studentDob;
private String studentGender;
private String studentEmail;
private String studentContactNo;
private String studentAddress;
private int studentZipCode;
private String studentState;
private String studentCcity;
private long studentEducationId;
private float studentEducationSscMarks;
private int studentEducationSscPassYear;
private float studentEducationHsscMarks;
private String studentEducationHsscStream;
private int studentEducationHsscPasYear;
private String studentEducationGradCourse;
private float studentEducationGradsCgpa;
private int studentEducationGradPassYear;
private String StudentEducationPgCourse;
private float studentEducationPgCgpa;
private int studentEducationPgPassYear;
private int studentEducationYear;
private String studentEducationGapReason;
private String studentcertificationId;
private String studentcertificationOrgiDetails;
private String studentcertificationTitle;
private String studentcertificationIssueDate;
public String getStudentGender() {
return studentGender;
}
public void setStudentGender(String studentGender) {
this.studentGender = studentGender;
}
public String getStudentcertificationIssueDate() {
return studentcertificationIssueDate;
}
public void setStudentcertificationIssueDate(String studentcertificationIssueDate) {
this.studentcertificationIssueDate = studentcertificationIssueDate;
}
public String getStudentRollNo() {
return studentRollNo;
}
public void setStudentRollNo(String studentRollNo) {
this.studentRollNo = studentRollNo;
}
public String getStudentFullName() {
return studentFullName;
}
public void setStudentFullName(String studentFullName) {
this.studentFullName = studentFullName;
}
public String getStudentFatherName() {
return studentFatherName;
}
public void setStudentFatherName(String studentFatherName) {
this.studentFatherName = studentFatherName;
}
public String getStudentMotherName() {
return studentMotherName;
}
public void setStudentMotherName(String studentMotherName) {
this.studentMotherName = studentMotherName;
}
public String getStudentDob() {
return studentDob;
}
public void setStudentDob(String studentDob) {
this.studentDob = studentDob;
}
public String getStudentEmail() {
return studentEmail;
}
public void setStudentEmail(String studentEmail) {
this.studentEmail = studentEmail;
}
public String getStudentContactNo() {
return studentContactNo;
}
public void setStudentContactNo(String studentContactNo) {
this.studentContactNo = studentContactNo;
}
public String getStudentAddress() {
return studentAddress;
}
public void setStudentAddress(String studentAddress) {
this.studentAddress = studentAddress;
}
public int getStudentZipCode() {
return studentZipCode;
}
public void setStudentZipCode(int studentZipCode) {
this.studentZipCode = studentZipCode;
}
public String getStudentState() {
return studentState;
}
public void setStudentState(String studentState) {
this.studentState = studentState;
}
public String getStudentCcity() {
return studentCcity;
}
public void setStudentCcity(String studentCcity) {
this.studentCcity = studentCcity;
}
public long getStudentEducationId() {
return studentEducationId;
}
public void setStudentEducationId(long studentEducationId) {
this.studentEducationId = studentEducationId;
}
public float getStudentEducationSscMarks() {
return studentEducationSscMarks;
}
public void setStudentEducationSscMarks(float studentEducationSscMarks) {
this.studentEducationSscMarks = studentEducationSscMarks;
}
public int getStudentEducationSscPassYear() {
return studentEducationSscPassYear;
}
public void setStudentEducationSscPassYear(int studentEducationSscPassYear) {
this.studentEducationSscPassYear = studentEducationSscPassYear;
}
public float getStudentEducationHsscMarks() {
return studentEducationHsscMarks;
}
public void setStudentEducationHsscMarks(float studentEducationHsscMarks) {
this.studentEducationHsscMarks = studentEducationHsscMarks;
}
public String getStudentEducationHsscStream() {
return studentEducationHsscStream;
}
public void setStudentEducationHsscStream(String studentEducationHsscStream) {
this.studentEducationHsscStream = studentEducationHsscStream;
}
public int getStudentEducationHsscPasYear() {
return studentEducationHsscPasYear;
}
public void setStudentEducationHsscPasYear(int studentEducationHsscPasYear) {
this.studentEducationHsscPasYear = studentEducationHsscPasYear;
}
public String getStudentEducationGradCourse() {
return studentEducationGradCourse;
}
public void setStudentEducationGradCourse(String studentEducationGradCourse) {
this.studentEducationGradCourse = studentEducationGradCourse;
}
public float getStudentEducationGradsCgpa() {
return studentEducationGradsCgpa;
}
public void setStudentEducationGradsCgpa(float studentEducationGradsCgpa) {
this.studentEducationGradsCgpa = studentEducationGradsCgpa;
}
public int getStudentEducationGradPassYear() {
return studentEducationGradPassYear;
}
public void setStudentEducationGradPassYear(int studentEducationGradPassYear) {
this.studentEducationGradPassYear = studentEducationGradPassYear;
}
public String getStudentEducationPgCourse() {
return StudentEducationPgCourse;
}
public void setStudentEducationPgCourse(String studentEducationPgCourse) {
StudentEducationPgCourse = studentEducationPgCourse;
}
public float getStudentEducationPgCgpa() {
return studentEducationPgCgpa;
}
public void setStudentEducationPgCgpa(float studentEducationPgCgpa) {
this.studentEducationPgCgpa = studentEducationPgCgpa;
}
public int getStudentEducationPgPassYear() {
return studentEducationPgPassYear;
}
public void setStudentEducationPgPassYear(int studentEducationPgPassYear) {
this.studentEducationPgPassYear = studentEducationPgPassYear;
}
public int getStudentEducationYear() {
return studentEducationYear;
}
public void setStudentEducationYear(int studentEducationYear) {
this.studentEducationYear = studentEducationYear;
}
public String getStudentEducationGapReason() {
return studentEducationGapReason;
}
public void setStudentEducationGapReason(String studentEducationGapReason) {
this.studentEducationGapReason = studentEducationGapReason;
}
public String getStudentcertificationId() {
return studentcertificationId;
}
public void setStudentcertificationId(String studentcertificationId) {
this.studentcertificationId = studentcertificationId;
}
public String getStudentcertificationOrgiDetails() {
return studentcertificationOrgiDetails;
}
public void setStudentcertificationOrgiDetails(String studentcertificationOrgiDetails) {
this.studentcertificationOrgiDetails = studentcertificationOrgiDetails;
}
public String getStudentcertificationTitle() {
return studentcertificationTitle;
}
public void setStudentcertificationTitle(String studentcertificationTitle) {
this.studentcertificationTitle = studentcertificationTitle;
}
public ExcelPojo() {
}
}
// REST CONTROLLER
#GetMapping("/download/{companyId}")
public ResponseEntity<InputStreamResource> excelCustomersReport(#PathVariable long companyId) throws IOException {
List<ExcelPojo> customers = companyService.load(companyId);
ByteArrayInputStream in = ExcelHelper.tutorialsToExcel(customers);
// return IOUtils.toByteArray(in);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename="+companyId+".xlsx");
return ResponseEntity
.ok()
.headers(headers)
.body(new InputStreamResource(in));
}
// Service implementation
public List<ExcelPojo> load(long companyId) {
Set<StudentPersonalDetails> list= getPersonalDetails(companyId);
List<ExcelPojo> tutorials = new ArrayList<ExcelPojo>();
for(StudentPersonalDetails student :list) {
ExcelPojo excel = new ExcelPojo();
excel.setStudentRollNo(student.getRollNo());
excel.setStudentFullName(student.getFullName());
excel.setStudentFatherName(student.getFatherName());
excel.setStudentMotherName(student.getMotherName());
if(student.getGender()==0){
excel.setStudentGender("Male");
}else {
excel.setStudentGender("Female");
}
excel.setStudentEmail(student.getEmail());
excel.setStudentContactNo(student.getContactNo());
excel.setStudentAddress(student.getAddress());
excel.setStudentZipCode(student.getZipCode());
excel.setStudentState(student.getState());
excel.setStudentCcity(student.getCity());
StudentEducationalDetails education = studentEduDao.findByStu(student);
excel.setStudentEducationId(education.getId());
excel.setStudentEducationSscMarks(education.getSscMarks());
excel.setStudentEducationSscPassYear(education.getSscPassYear());
excel.setStudentEducationHsscMarks(education.getHsscMarks());
excel.setStudentEducationHsscStream(education.getHsscStream());
excel.setStudentEducationHsscPasYear(education.getHsscPasYear());
excel.setStudentEducationGradCourse(education.getGradCourse());
excel.setStudentEducationGradsCgpa(education.getGradsCgpa());
excel.setStudentEducationGradPassYear(education.getGradPassYear());
excel.setStudentEducationPgCourse(education.getPgCourse());
excel.setStudentEducationPgCgpa(education.getPgCgpa());
excel.setStudentEducationPgPassYear(education.getPgPassYear());
excel.setStudentEducationYear(education.getYear());
excel.setStudentEducationGapReason(education.getGapReason());
List<StudentCertification> certi = studentCertiDao.findByStu(student);
if(certi.isEmpty()) {
excel.setStudentcertificationId(null);
excel.setStudentcertificationOrgiDetails(null);
excel.setStudentcertificationTitle(null);
excel.setStudentcertificationIssueDate(null);
}else {
StringBuffer sb[] = new StringBuffer[4];
boolean isFirst= true;
for(StudentCertification certifica :certi) {
if(! isFirst) {
sb[0].append(", ");
sb[1].append(", ");
sb[2].append(", ");
sb[3].append(", ");
}
sb[0].append(certifica.getCertificateId());
sb[2].append(certifica.getCertiTitle());
sb[1].append(certifica.getOrgiDetails());
sb[3].append(certifica.getIssueDate());
isFirst= false; }
excel.setStudentcertificationId(sb[0].toString());
excel.setStudentcertificationOrgiDetails(sb[1].toString());
excel.setStudentcertificationTitle(sb[2].toString());
excel.setStudentcertificationIssueDate(sb[3].toString());
}
tutorials.add(excel);
}
return tutorials;
}
the javax.persistence.NonUniqueResultException error is typical of JPA not POI, add the code of your query.
Usually occurs when you use the getSingleResult () method and the query returns more than one result.

The request sent by the client was syntactically incorrect. Spring Backend

I stuck at this problem with Post Request, which gives me error 400 bad request, i have checked the JSON RequestBody via okHttpInterceptor by Retrofit and Json validated correctly. I don't know what's the problem with requestBody. it works with ModelAttribute though, but i want to pass data as requestBody.
This is my Spring Controller ->
#RequestMapping(value = "/updateProfile", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
#ResponseBody
public BasicResponse farmerUpdateProfile(#RequestBody UpdateFarmerRequest updateFarmerRequest, HttpServletRequest request) {
BasicResponse response = new BasicResponse();
// get authentication token and farmer ID from header
String requestAuthToken = (String) request.getHeader(MOBILE_AUTH);
String requestFarmerId = (String) request.getHeader(FARMER_ID);
// update farmer data, if id and AuthTokens are same...
// Validate Authentication Token
try {
if (!farmerMobileManager.validateAuthToken(requestFarmerId, requestAuthToken)) {
response.setErrorCode(ErrorCode.BAD_CREDENTIALS);
response.setResponse("Bad request error");
return response;
}
farmerMobileManager.updateFarmerRequest(updateFarmerRequest, response, requestFarmerId);
} catch (Exception ex) {
System.out.println(ex.getMessage());
response.setErrorCode(ErrorCode.INTERNAL_SERVER_ERROR);
response.setResponse("Error fetching prescriptions");
}
return response;
}
This is my UpdateFarmerRequestClass.
public class UpdateFarmerRequest {
#JsonProperty("farmer")
private Farmer farmer;
public void setFarmer(Farmer farmer) {
this.farmer = farmer;
}
public Farmer getFarmer() {
return farmer;
}
}
This is my Farmerclass ->
public class Farmer extends User {
private String farmerReferenceId;
private String cropId;
private String nomineeName;
private NomineeRelation nomineeRelation;
private String stateName;
private String mandalName;
private String villageName;
private String houseNumber;
private Boolean smartPhoneUser;
private SocialStatus socialStatus;
private EducationLevel educationLevel;
private String aadharNumber;
private String stateId;
private String districtId;
private String mandalId;
private String villageId;
private Boolean oneTimeDataEntered = false;
private ArrayList<CropData> cropData;
public String getHouseNumber() {
return houseNumber;
}
public String getCropId() {
return cropId;
}
public void setCropId(String cropId) {
this.cropId = cropId;
}
public List<CropData> getCropData() {
return cropData;
}
public void setCropData(List<CropData> cropData) {
List<CropData> newCropData = new ArrayList<>();
for (CropData cropDataItem : cropData) {
Boolean didFind = false;
for (CropData farmerCropData : this.cropData) {
// if it matched in db, update the record.
if (farmerCropData.getCrop().name().equals(cropDataItem.getCrop().name())) {
// update that you got the db record
didFind = true;
farmerCropData.setCropAcres(cropDataItem.getCropAcres());
farmerCropData.setCropName(cropDataItem.getCropName());
farmerCropData.setCropYield(cropDataItem.getCropYield());
}
}
if (!didFind) {
// if you didn't fnd the record, add to new crop data
newCropData.add(cropDataItem);
}
this.cropData.addAll(newCropData);
}
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public Farmer() {
super();
}
public String getNomineeName() {
return nomineeName;
}
public void setNomineeName(String nomineeName) {
this.nomineeName = nomineeName;
}
public NomineeRelation getNomineeRelation() {
return nomineeRelation;
}
public void setNomineeRelation(NomineeRelation nomineeRelation) {
this.nomineeRelation = nomineeRelation;
}
public String getMandalName() {
return mandalName;
}
public void setMandalName(String mandalName) {
this.mandalName = mandalName;
}
public String getVillageName() {
return villageName;
}
public void setVillageName(String villageName) {
this.villageName = villageName;
}
public Boolean getSmartPhoneUser() {
return smartPhoneUser;
}
public void setSmartPhoneUser(Boolean smartPhoneUser) {
this.smartPhoneUser = smartPhoneUser;
}
public SocialStatus getSocialStatus() {
return socialStatus;
}
public void setSocialStatus(SocialStatus socialStatus) {
this.socialStatus = socialStatus;
}
public EducationLevel getEducationLevel() {
return educationLevel;
}
public void setEducationLevel(EducationLevel educationLevel) {
this.educationLevel = educationLevel;
}
public String getAadharNumber() {
return aadharNumber;
}
public void setAadharNumber(String aadharNumber) {
this.aadharNumber = aadharNumber;
}
public String getFarmerReferenceId() {
return farmerReferenceId;
}
public void setFarmerReferenceId(String farmerReferenceId) {
this.farmerReferenceId = farmerReferenceId;
}
public String getStateId() {
return stateId;
}
public void setStateId(String stateId) {
this.stateId = stateId;
}
public String getDistrictId() {
return districtId;
}
public void setDistrictId(String districtId) {
this.districtId = districtId;
}
public String getMandalId() {
return mandalId;
}
public void setMandalId(String mandalId) {
this.mandalId = mandalId;
}
public String getVillageId() {
return villageId;
}
public void setVillageId(String villageId) {
this.villageId = villageId;
}
public Boolean getOneTimeDataEntered() {
return oneTimeDataEntered;
}
public void setOneTimeDataEntered(Boolean oneTimeDataEntered) {
this.oneTimeDataEntered = oneTimeDataEntered;
}
public List<String> collectErrors() {
List<String> errors = new ArrayList<String>();
if (StringUtils.isEmpty(this.villageId)) {
errors.add("villageId");
}
// if (StringUtils.isEmpty(this.nomineeName)) {
// errors.add("nomineeName");
// }
if (StringUtils.isEmpty(this.getFirstName())) {
errors.add("firstName");
}
if (StringUtils.isEmpty(this.getPhoneNumber()) || !CommonUtils.validatePhoneNumber(this.getPhoneNumber())) {
errors.add("phoneNumber");
}
return errors;
}
public List<String> collectSignUpErrors() {
List<String> errors = new ArrayList<String>();
if (StringUtils.isEmpty(this.villageId)) {
errors.add("villageId");
}
if (StringUtils.isEmpty(this.getFirstName())) {
errors.add("firstName");
}
if (StringUtils.isEmpty(this.getPhoneNumber()) || !CommonUtils.validatePhoneNumber(this.getPhoneNumber())) {
errors.add("phoneNumber");
}
return errors;
}
public static class Constants extends User.Constants {
public static final String FARMER_REFERENCE_ID = "farmerReferenceId";
public static final String AADHAR_NUMBER = "aadharNumber";
public static final String MANDAL_ID = "mandalId";
public static final String VILLAGE_ID = "villageId";
public static final String FARMER_ID = "_id";
}
}
this is my RequestBody that i am sending in POSTMAN.
RequestBody ->
{
"farmer": {
"city": "",
"mandalName": "",
"stateName": "",
"villageName": "",
"countryCode": "+",
"cropData": [{
"crop": "RICE",
"cropAcres": 1.0,
"cropName": "RICE",
"cropYield": 2.0
}, {
"crop": "PADDY",
"cropAcres": 4.0,
"cropName": "PADDY",
"cropYield": 5.0
}
],
"cropId": "",
"districtId": "",
"farmerReferenceId": "",
"firstName": "",
"houseNumber": "",
"id": "",
"mandalId": "",
"phoneNumber": "",
"stateId": "",
"villageId": ""
}
}
The Data are not empty, but i am purposely not filling it for privacy purpose.
I have solved my problem, it was naming convention problem, as i was passing cropData as "cropData", while at server Side it was "CropData."

Retrofit2: Expected a string but was BEGIN_ARRAY (Android Studio)

I have an error when retrieving json data with retrofit2 in Android Studio. Last time i was try to retrieving data with json only 1 Response model, but now i just need to retrieving json data more than 1 table from database.
Error
java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 20 path $.pesan
No adapter attached; skipping layout
My ResponseModel.class
public class ResponseModel {
String kode, pesan;
List<QuestionModel> result_question; //But the problem is coming when i try to retrieving another json from another table(2)
List<UserDataModel> result; //i was success with this(1)
public String getKode() {
return kode;
}
public void setKode(String kode) {
this.kode = kode;
}
public String getPesan() {
return pesan;
}
public void setPesan(String pesan) {
this.pesan = pesan;
}
public List<QuestionModel> getResult_question() {
return result_question;
}
public void setResult_question(List<QuestionModel> result_question) {
this.result_question = result_question;
}
public List<UserDataModel> getResult() {
return result;
}
public void setResult(List<UserDataModel> result) {
this.result = result;
}
}
My QuestionModel.class
public class QuestionModel {
String id_question, id_user, judul, waktu, tanggal, jml_like, aktif;
public String getId_question() {
return id_question;
}
public void setId_question(String id_question) {
this.id_question = id_question;
}
public String getId_user() {
return id_user;
}
public void setId_user(String id_user) {
this.id_user = id_user;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getWaktu() {
return waktu;
}
public void setWaktu(String waktu) {
this.waktu = waktu;
}
public String getTanggal() {
return tanggal;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getJml_like() {
return jml_like;
}
public void setJml_like(String jml_like) {
this.jml_like = jml_like;
}
public String getAktif() {
return aktif;
}
public void setAktif(String aktif) {
this.aktif = aktif;
}
}
My ApiRequest
#GET(url_question_list)
Call<ResponseModel> getQuestionData();
Enqueu
getData.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
pd.dismiss();
Log.d(TAG,"onResponse: "+ response.body().getKode());
mList = response.body().getResult_question();
mAdapter = new AdapterQuestion(MainActivity.this, mList);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
pd.dismiss();
Log.e(TAG, "onFailure: "+t.getMessage());
}
});
JSON Format
{
"kode": 1,
"pesan": [
{
"id_question": "2",
"id_user": "8",
"judul": "Title1",
"waktu": "11:22:10",
"tanggal": "20-06-2018",
"jml_like": "0",
"aktif": "Y"
},
{
"id_question": "1",
"id_user": "9",
"judul": "Title2",
"waktu": "11:22:20",
"tanggal": "19-02-2012",
"jml_like": "1",
"aktif": "Y"
}
]
}
Thank for your help.
UPDATE: SOLVED
'Pesan' should be List<>
In your ResponseModel you define String pesan, while in the json file pesan is a List<QuestionModel>
make some changes in response model class like below ..
public class Response {
#SerializedName("kode")
private Integer kode;
#SerializedName("pesan")
private List<Pesan> pesan = null;
public Integer getKode() {
return kode;
}
public void setKode(Integer kode) {
this.kode = kode;
}
public List<Pesan> getPesan() {
return pesan;
}
public void setPesan(List<Pesan> pesan) {
this.pesan = pesan;
}
}
and also make one pesan pojo class.
public class Pesan {
#SerializedName("id_question")
private String idQuestion;
#SerializedName("id_user")
private String idUser;
#SerializedName("judul")
private String judul;
#SerializedName("waktu")
private String waktu;
#SerializedName("tanggal")
private String tanggal;
#SerializedName("jml_like")
private String jmlLike;
#SerializedName("aktif")
private String aktif;
public String getIdQuestion() {
return idQuestion;
}
public void setIdQuestion(String idQuestion) {
this.idQuestion = idQuestion;
}
public String getIdUser() {
return idUser;
}
public void setIdUser(String idUser) {
this.idUser = idUser;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getWaktu() {
return waktu;
}
public void setWaktu(String waktu) {
this.waktu = waktu;
}
public String getTanggal() {
return tanggal;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getJmlLike() {
return jmlLike;
}
public void setJmlLike(String jmlLike) {
this.jmlLike = jmlLike;
}
public String getAktif() {
return aktif;
}
public void setAktif(String aktif) {
this.aktif = aktif;
}
}
above code working only you provide json format in question if any error then pl provide full json from server given response.
because answer is based on question json format based.

How to deserialize a JSON Object in a multidimensional array

I have this JSON data and I would like to deserialize it with Android to get it as an object to use in my class.
I get this folowing error :
Could not read JSON: Unrecognized field "card_details"
[
{
"id": "9",
"cat_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"app_id": "null",
"status": "1",
"lft": "1",
"rgt": "2",
"parent_cat_id": "0",
"added_date": "2017-01-12 12:41:29",
"last_edit_date": "2017-01-12 12:46:09",
"language_id": "0",
"category_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"name": "Sport",
"description": "This is sport category",
"image": "notitia/USR-70903638005256656/app-content/cat-img-da1161af03df255a989f8df5fc2e15bd.png",
"tags": "",
"custom_url": "sport",
"card_details": {
"nom_carte": "Pinacolada",
"prix": "5000",
"image": "notitia/USR-44043694343417880/app-content/e0fa7beb401e8fe77727f5a8241ff872.jpg",
"validity": "1"
}
}
]
Here is my AsyncTask to retrieve the data:
private class HttpRequestTaskCarte extends AsyncTask<Void,Void,Item[]> {
#Override
protected Item[] doInBackground(Void... params) {
try {
final String url = "http://domain.com/link.php?target=multi";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Item[] greeting = restTemplate.getForObject(url, Item[].class);
return greeting;
} catch (Exception e) {
//Toast.makeText(getActivity(), "Error Loading !", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
protected void onPreExecute(){
progressDialog = new ProgressDialog(getActivity(),
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("chargement des elements...");
progressDialog.show();
}
#Override
protected void onPostExecute(Item[] greeting) {
Log.d("okokok",""+greeting.length);
progressDialog.dismiss();
}
}
And here is the class that I am using to deserialize:
public class Item {
private List<card_details> carte;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCat_id() {
return cat_id;
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getApp_id() {
return app_id;
}
public void setApp_id(String app_id) {
this.app_id = app_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLft() {
return lft;
}
public void setLft(String lft) {
this.lft = lft;
}
public String getRgt() {
return rgt;
}
public void setRgt(String rgt) {
this.rgt = rgt;
}
public String getParent_cat_id() {
return parent_cat_id;
}
public void setParent_cat_id(String parent_cat_id) {
this.parent_cat_id = parent_cat_id;
}
public String getAdded_date() {
return added_date;
}
public void setAdded_date(String added_date) {
this.added_date = added_date;
}
public String getLast_edit_date() {
return last_edit_date;
}
public void setLast_edit_date(String last_edit_date) {
this.last_edit_date = last_edit_date;
}
public String getLanguage_id() {
return language_id;
}
public void setLanguage_id(String language_id) {
this.language_id = language_id;
}
public String getCategory_id() {
return category_id;
}
public void setCategory_id(String category_id) {
this.category_id = category_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getCustom_url() {
return custom_url;
}
public void setCustom_url(String custom_url) {
this.custom_url = custom_url;
}
public List<Detail_cartes> getCarte() {
return carte;
}
public void setCarte(List<Detail_cartes> carte) {
this.carte = carte;
}
public static class Detail_cartes{
private String nom_carte ;
private String prix ;
private String image ;
private String validity ;
}
}
JSONArray array=new JSONArray(your data);
JSONObject obj=array.getJSONObject(0);
JSONObject cardDetail=obj.getJSONObject("card_details");
Hii u can use the following code:
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}

Spark: Mapping RDD to RDD returning nullpointer Exception

In my logic, I am attempting to map a JDBCRDD - TopologyRDD over to a JavaBean of JavaRDD.
TopologyRDD.count() returns the CORRECT number of rows, so I know the data was loaded in correctly. I also mapped TopologyRDD to a List just to confirm the data was loaded in, and it loaded in the data just fine.
Problem: When mapping TopologyRDD to MODEL_TOPOLOGYRDD, the MODEL_TOPOLOGYRDD.count() action is returning a nullpointer exception error.
Model:
public class modelTopology implements Serializable {
private String A_TYPE;
private String Z_TYPE;
private String A_CLLI;
private String Z_CLLI;
private String A_HOSTNAME;
private String Z_HOSTNAME;
private String A_LOCATION;
private String A_LOC_TYPE;
private String Z_LOCATION;
private String Z_LOC_TYPE;
private String A_SHELF;
private String A_SLOT;
private String A_CARD;
private String A_PORT;
private String A_INTERFACE;
private String A_IF_DESC;
private String Z_SHELF;
private String Z_SLOT;
private String Z_CARD;
private String Z_PORT;
private String Z_INTERFACE;
private String Z_IF_DESC;
private String A_CARD_NAME;
private String Z_CARD_NAME;
private String PHY_CIRCUIT_ID;
private String LAG_CIRCUIT_ID;
private String PHY_CIRCUIT_ALIAS;
private String A_VENDOR;
private String A_MODEL;
private String A_TECHNOLOGY;
private String Z_VENDOR;
private String Z_MODEL;
private String Z_TECHNOLOGY;
private String A_EH_ELEMENT_ID;
private String A_EH_MACHINE_ID;
private String Z_EH_ELEMENT_ID;
private String Z_EH_MACHINE_ID;
private String A_EH_SPEED;
private String Z_EH_SPEED;
private String A_EH_SPEED1;
private String Z_EH_SPEED1;
private String A_EH_EHEALTH_DOMAIN;
private String Z_EH_EHEALTH_DOMAIN;
private String A_MRTG_HOSTID;
private String A_MRTG_GRPID;
private String A_MRTG_IFID;
private String Z_MRTG_HOSTID;
private String Z_MRTG_GRPID;
private String Z_MRTG_IFID;
private String A_MGMT_IP;
private String Z_MGMT_IP;
private String A_IF_INDEX;
private String Z_IF_INDEX;
private String IS_PROD;
private String TOPOLOGY_KEY;
private String COMMIT_TS;
public void setA_TYPE(String A_TYPE) {
this.A_TYPE = A_TYPE;
}
public void setZ_TYPE(String Z_TYPE) {
this.Z_TYPE = Z_TYPE;
}
public void setA_CLLI(String A_CLLI) {
this.A_CLLI = A_CLLI;
}
public void setZ_CLLI(String Z_CLLI) {
this.Z_CLLI = Z_CLLI;
}
public void setA_HOSTNAME(String A_HOSTNAME) {
this.A_HOSTNAME = A_HOSTNAME;
}
public void setZ_HOSTNAME(String Z_HOSTNAME) {
this.Z_HOSTNAME = Z_HOSTNAME;
}
public void setA_LOCATION(String A_LOCATION) {
this.A_LOCATION = A_LOCATION;
}
public void setA_LOC_TYPE(String A_LOC_TYPE) {
this.A_LOC_TYPE = A_LOC_TYPE;
}
public void setZ_LOCATION(String Z_LOCATION) {
this.Z_LOCATION = Z_LOCATION;
}
public void setZ_LOC_TYPE(String Z_LOC_TYPE) {
this.Z_LOC_TYPE = Z_LOC_TYPE;
}
public void setA_SHELF(String A_SHELF) {
this.A_SHELF = A_SHELF;
}
public void setA_SLOT(String A_SLOT) {
this.A_SLOT = A_SLOT;
}
public void setA_CARD(String A_CARD) {
this.A_CARD = A_CARD;
}
public void setA_PORT(String A_PORT) {
this.A_PORT = A_PORT;
}
public void setA_INTERFACE(String A_INTERFACE) {
this.A_INTERFACE = A_INTERFACE;
}
public void setA_IF_DESC(String A_IF_DESC) {
this.A_IF_DESC = A_IF_DESC;
}
public void setZ_SHELF(String Z_SHELF) {
this.Z_SHELF = Z_SHELF;
}
public void setZ_SLOT(String Z_SLOT) {
this.Z_SLOT = Z_SLOT;
}
public void setZ_CARD(String Z_CARD) {
this.Z_CARD = Z_CARD;
}
public void setZ_PORT(String Z_PORT) {
this.Z_PORT = Z_PORT;
}
public void setZ_INTERFACE(String Z_INTERFACE) {
this.Z_INTERFACE = Z_INTERFACE;
}
public void setZ_IF_DESC(String Z_IF_DESC) {
this.Z_IF_DESC = Z_IF_DESC;
}
public void setA_CARD_NAME(String A_CARD_NAME) {
this.A_CARD_NAME = A_CARD_NAME;
}
public void setZ_CARD_NAME(String Z_CARD_NAME) {
this.Z_CARD_NAME = Z_CARD_NAME;
}
public void setPHY_CIRCUIT_ID(String PHY_CIRCUIT_ID) {
this.PHY_CIRCUIT_ID = PHY_CIRCUIT_ID;
}
public void setLAG_CIRCUIT_ID(String LAG_CIRCUIT_ID) {
this.LAG_CIRCUIT_ID = LAG_CIRCUIT_ID;
}
public void setPHY_CIRCUIT_ALIAS(String PHY_CIRCUIT_ALIAS) {
this.PHY_CIRCUIT_ALIAS = PHY_CIRCUIT_ALIAS;
}
public void setA_VENDOR(String A_VENDOR) {
this.A_VENDOR = A_VENDOR;
}
public void setA_MODEL(String A_MODEL) {
this.A_MODEL = A_MODEL;
}
public void setA_TECHNOLOGY(String A_TECHNOLOGY) {
this.A_TECHNOLOGY = A_TECHNOLOGY;
}
public void setZ_VENDOR(String Z_VENDOR) {
this.Z_VENDOR = Z_VENDOR;
}
public void setZ_MODEL(String Z_MODEL) {
this.Z_MODEL = Z_MODEL;
}
public void setZ_TECHNOLOGY(String Z_TECHNOLOGY) {
this.Z_TECHNOLOGY = Z_TECHNOLOGY;
}
public void setA_EH_ELEMENT_ID(String A_EH_ELEMENT_ID) {
this.A_EH_ELEMENT_ID = A_EH_ELEMENT_ID;
}
public void setA_EH_MACHINE_ID(String A_EH_MACHINE_ID) {
this.A_EH_MACHINE_ID = A_EH_MACHINE_ID;
}
public void setZ_EH_ELEMENT_ID(String Z_EH_ELEMENT_ID) {
this.Z_EH_ELEMENT_ID = Z_EH_ELEMENT_ID;
}
public void setZ_EH_MACHINE_ID(String Z_EH_MACHINE_ID) {
this.Z_EH_MACHINE_ID = Z_EH_MACHINE_ID;
}
public void setA_EH_SPEED(String A_EH_SPEED) {
this.A_EH_SPEED = A_EH_SPEED;
}
public void setZ_EH_SPEED(String Z_EH_SPEED) {
this.Z_EH_SPEED = Z_EH_SPEED;
}
public void setA_EH_SPEED1(String A_EH_SPEED1) {
this.A_EH_SPEED1 = A_EH_SPEED1;
}
public void setZ_EH_SPEED1(String Z_EH_SPEED1) {
this.Z_EH_SPEED1 = Z_EH_SPEED1;
}
public void setA_EH_EHEALTH_DOMAIN(String A_EH_EHEALTH_DOMAIN) {
this.A_EH_EHEALTH_DOMAIN = A_EH_EHEALTH_DOMAIN;
}
public void setZ_EH_EHEALTH_DOMAIN(String Z_EH_EHEALTH_DOMAIN) {
this.Z_EH_EHEALTH_DOMAIN = Z_EH_EHEALTH_DOMAIN;
}
public void setA_MRTG_HOSTID(String A_MRTG_HOSTID) {
this.A_MRTG_HOSTID = A_MRTG_HOSTID;
}
public void setA_MRTG_GRPID(String A_MRTG_GRPID) {
this.A_MRTG_GRPID = A_MRTG_GRPID;
}
public void setA_MRTG_IFID(String A_MRTG_IFID) {
this.A_MRTG_IFID = A_MRTG_IFID;
}
public void setZ_MRTG_HOSTID(String Z_MRTG_HOSTID) {
this.Z_MRTG_HOSTID = Z_MRTG_HOSTID;
}
public void setZ_MRTG_GRPID(String Z_MRTG_GRPID) {
this.Z_MRTG_GRPID = Z_MRTG_GRPID;
}
public void setZ_MRTG_IFID(String Z_MRTG_IFID) {
this.Z_MRTG_IFID = Z_MRTG_IFID;
}
public void setA_MGMT_IP(String A_MGMT_IP) {
this.A_MGMT_IP = A_MGMT_IP;
}
public void setZ_MGMT_IP(String Z_MGMT_IP) {
this.Z_MGMT_IP = Z_MGMT_IP;
}
public void setA_IF_INDEX(String A_IF_INDEX) {
this.A_IF_INDEX = A_IF_INDEX;
}
public void setZ_IF_INDEX(String Z_IF_INDEX) {
this.Z_IF_INDEX = Z_IF_INDEX;
}
public void setIS_PROD(String IS_PROD) {
this.IS_PROD = IS_PROD;
}
public void setTOPOLOGY_KEY(String TOPOLOGY_KEY) {
this.TOPOLOGY_KEY = TOPOLOGY_KEY;
}
public void setCOMMIT_TS(String COMMIT_TS) {
this.COMMIT_TS = COMMIT_TS;
}
public String getA_TYPE() {
return A_TYPE;
}
public String getZ_TYPE() {
return Z_TYPE;
}
public String getA_CLLI() {
return A_CLLI;
}
public String getZ_CLLI() {
return Z_CLLI;
}
public String getA_HOSTNAME() {
return A_HOSTNAME;
}
public String getZ_HOSTNAME() {
return Z_HOSTNAME;
}
public String getA_LOCATION() {
return A_LOCATION;
}
public String getA_LOC_TYPE() {
return A_LOC_TYPE;
}
public String getZ_LOCATION() {
return Z_LOCATION;
}
public String getZ_LOC_TYPE() {
return Z_LOC_TYPE;
}
public String getA_SHELF() {
return A_SHELF;
}
public String getA_SLOT() {
return A_SLOT;
}
public String getA_CARD() {
return A_CARD;
}
public String getA_PORT() {
return A_PORT;
}
public String getA_INTERFACE() {
return A_INTERFACE;
}
public String getA_IF_DESC() {
return A_IF_DESC;
}
public String getZ_SHELF() {
return Z_SHELF;
}
public String getZ_SLOT() {
return Z_SLOT;
}
public String getZ_CARD() {
return Z_CARD;
}
public String getZ_PORT() {
return Z_PORT;
}
public String getZ_INTERFACE() {
return Z_INTERFACE;
}
public String getZ_IF_DESC() {
return Z_IF_DESC;
}
public String getA_CARD_NAME() {
return A_CARD_NAME;
}
public String getZ_CARD_NAME() {
return Z_CARD_NAME;
}
public String getPHY_CIRCUIT_ID() {
return PHY_CIRCUIT_ID;
}
public String getLAG_CIRCUIT_ID() {
return LAG_CIRCUIT_ID;
}
public String getPHY_CIRCUIT_ALIAS() {
return PHY_CIRCUIT_ALIAS;
}
public String getA_VENDOR() {
return A_VENDOR;
}
public String getA_MODEL() {
return A_MODEL;
}
public String getA_TECHNOLOGY() {
return A_TECHNOLOGY;
}
public String getZ_VENDOR() {
return Z_VENDOR;
}
public String getZ_MODEL() {
return Z_MODEL;
}
public String getZ_TECHNOLOGY() {
return Z_TECHNOLOGY;
}
public String getA_EH_ELEMENT_ID() {
return A_EH_ELEMENT_ID;
}
public String getA_EH_MACHINE_ID() {
return A_EH_MACHINE_ID;
}
public String getZ_EH_ELEMENT_ID() {
return Z_EH_ELEMENT_ID;
}
public String getZ_EH_MACHINE_ID() {
return Z_EH_MACHINE_ID;
}
public String getA_EH_SPEED() {
return A_EH_SPEED;
}
public String getZ_EH_SPEED() {
return Z_EH_SPEED;
}
public String getA_EH_SPEED1() {
return A_EH_SPEED1;
}
public String getZ_EH_SPEED1() {
return Z_EH_SPEED1;
}
public String getA_EH_EHEALTH_DOMAIN() {
return A_EH_EHEALTH_DOMAIN;
}
public String getZ_EH_EHEALTH_DOMAIN() {
return Z_EH_EHEALTH_DOMAIN;
}
public String getA_MRTG_HOSTID() {
return A_MRTG_HOSTID;
}
public String getA_MRTG_GRPID() {
return A_MRTG_GRPID;
}
public String getA_MRTG_IFID() {
return A_MRTG_IFID;
}
public String getZ_MRTG_HOSTID() {
return Z_MRTG_HOSTID;
}
public String getZ_MRTG_GRPID() {
return Z_MRTG_GRPID;
}
public String getZ_MRTG_IFID() {
return Z_MRTG_IFID;
}
public String getA_MGMT_IP() {
return A_MGMT_IP;
}
public String getZ_MGMT_IP() {
return Z_MGMT_IP;
}
public String getA_IF_INDEX() {
return A_IF_INDEX;
}
public String getZ_IF_INDEX() {
return Z_IF_INDEX;
}
public String getIS_PROD() {
return IS_PROD;
}
public String getTOPOLOGY_KEY() {
return TOPOLOGY_KEY;
}
public String getCOMMIT_TS() {
return COMMIT_TS;
}
}
Code:
//Push into JDBC RDD Object
JdbcRDD<Object[]> TopologyJDBCRDD = new JdbcRDD(sc.sc(),oraclecon,"SELECT * FROM NPIDWUAT.FIOS_TOPOLOGY_STG WHERE ? = ?",1,1,1, new MapResult(),ClassManifestFactory$.MODULE$.fromClass(Object[].class));
//Convert to JavaRDD
JavaRDD<Object[]> TopologyRDD = JavaRDD.fromRDD(TopologyJDBCRDD, ClassManifestFactory$.MODULE$.fromClass(Object[].class));
System.out.println("Number of Records: " + TopologyRDD.count());
JavaRDD<modelTopology> MODEL_TOPOLOGYRDD = TopologyRDD.map(
new Function<Object[], modelTopology>() {
#Override
public modelTopology call(final Object[] line) throws Exception {
Object[] line2 = line;
for(int i=0;i<line2.length;i++){
if(line2[i].toString() == null){
line2[i] = "";
}
else{
line2[i] = line2[i].toString();
}
}
modelTopology toporow = new modelTopology();
toporow.setA_TYPE(line2[0].toString());
toporow.setZ_TYPE(line2[1].toString());
toporow.setA_CLLI(line2[2].toString());
toporow.setZ_CLLI(line2[3].toString());
toporow.setA_HOSTNAME(line2[4].toString());
toporow.setZ_HOSTNAME(line2[5].toString());
toporow.setA_LOCATION(line2[6].toString());
toporow.setA_LOC_TYPE(line2[7].toString());
toporow.setZ_LOCATION(line2[8].toString());
toporow.setZ_LOC_TYPE(line2[9].toString());
toporow.setA_SHELF(line2[10].toString());
toporow.setA_SLOT(line2[11].toString());
toporow.setA_CARD(line2[12].toString());
toporow.setA_PORT(line2[13].toString());
toporow.setA_INTERFACE(line2[14].toString());
toporow.setA_IF_DESC(line2[15].toString());
toporow.setZ_SHELF(line2[16].toString());
toporow.setZ_SLOT(line2[17].toString());
toporow.setZ_CARD(line2[18].toString());
toporow.setZ_PORT(line2[19].toString());
toporow.setZ_INTERFACE(line2[20].toString());
toporow.setZ_IF_DESC(line2[21].toString());
toporow.setA_CARD_NAME(line2[22].toString());
toporow.setZ_CARD_NAME(line2[23].toString());
toporow.setPHY_CIRCUIT_ID(line2[24].toString());
toporow.setLAG_CIRCUIT_ID(line2[25].toString());
toporow.setPHY_CIRCUIT_ALIAS(line2[26].toString());
toporow.setA_VENDOR(line2[27].toString());
toporow.setA_MODEL(line2[28].toString());
toporow.setA_TECHNOLOGY(line2[29].toString());
toporow.setZ_VENDOR(line2[30].toString());
toporow.setZ_MODEL(line2[31].toString());
toporow.setZ_TECHNOLOGY(line2[32].toString());
toporow.setA_EH_ELEMENT_ID(line2[33].toString());
toporow.setA_EH_MACHINE_ID(line2[34].toString());
toporow.setZ_EH_ELEMENT_ID(line2[35].toString());
toporow.setZ_EH_MACHINE_ID(line2[36].toString());
toporow.setA_EH_SPEED(line2[37].toString());
toporow.setZ_EH_SPEED(line2[38].toString());
toporow.setA_EH_SPEED1(line2[39].toString());
toporow.setZ_EH_SPEED1(line2[40].toString());
toporow.setA_EH_EHEALTH_DOMAIN(line2[41].toString());
toporow.setZ_EH_EHEALTH_DOMAIN(line2[42].toString());
toporow.setA_MRTG_HOSTID(line2[43].toString());
toporow.setA_MRTG_GRPID(line2[44].toString());
toporow.setA_MRTG_IFID(line2[45].toString());
toporow.setZ_MRTG_HOSTID(line2[46].toString());
toporow.setZ_MRTG_GRPID(line2[47].toString());
toporow.setZ_MRTG_IFID(line2[48].toString());
toporow.setA_MGMT_IP(line2[49].toString());
toporow.setZ_MGMT_IP(line2[50].toString());
toporow.setA_IF_INDEX(line2[51].toString());
toporow.setZ_IF_INDEX(line2[52].toString());
toporow.setIS_PROD(line2[53].toString());
toporow.setTOPOLOGY_KEY(line2[54].toString());
toporow.setCOMMIT_TS(line2[55].toString());
return toporow;
}
});
System.out.println("MODEL_TOPOLOGYRDD COUNT: " + MODEL_TOPOLOGYRDD.count());
Stacktrace:
Application Failed...org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 1.0 failed 1 times, most recent failure: Lost task 0.0 in stage 1.0 (TID 1, localhost): java.lang.NullPointerException
at com.verizon.npi.MainApp$1.call(MainApp.java:103)
at com.verizon.npi.MainApp$1.call(MainApp.java:96)
at org.apache.spark.api.java.JavaPairRDD$$anonfun$toScalaFunction$1.apply(JavaPairRDD.scala:999)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
at org.apache.spark.storage.MemoryStore.unrollSafely(MemoryStore.scala:249)
at org.apache.spark.CacheManager.putInBlockManager(CacheManager.scala:163)
at org.apache.spark.CacheManager.getOrCompute(CacheManager.scala:70)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:243)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:61)
at org.apache.spark.scheduler.Task.run(Task.scala:56)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:200)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
The only problem I can see with this code is if any line2[i] are null.
And if(line2[i].toString() == null) won't work because toString() never returns null for the Object class.
I see that you want any null values to become empty strings, so try this as your for-loop instead
for(int i = 0; i < line2.length; i++){
line2[i] = (line2[i] == null) ? "" : String.valueOf(line2[i]);
}
Note the use of String.valueOf, which altogether avoids the NullPointerException when trying to get the String value of objects.

Categories

Resources