我需要将JSON响应转换为Java Object,但我却是nullpointerException。 这是我的模型课:
public class Cheque {
private String payeeName;
private String accountNumber;
private String ifsCode;
private String micr;
private String bankName;
public Cheque() {
super();
// TODO Auto-generated constructor stub
}
public Cheque(String payeeName, String accountNumber, String ifsCode, String micr, String bankName) {
super();
this.payeeName = payeeName;
this.accountNumber = accountNumber;
this.ifsCode = ifsCode;
this.micr = micr;
this.bankName = bankName;
}
public String getPayeeName() {
return payeeName;
}
public void setPayeeName(String payeeName) {
this.payeeName = payeeName;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getIfsCode() {
return ifsCode;
}
public void setIfscCode(String ifsCode) {
this.ifsCode = ifsCode;
}
public String getMicr() {
return micr;
}
public void setMicr(String micr) {
this.micr = micr;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
下面,我将发布一种调用Python程序并从中获取Json响应的方法:
public class RunPython {
public static void main(String[] args) throws IOException,ScriptException,NullPointerException{
// TODO Auto-generated method stub
Process p = Runtime.getRuntime().exec("python <path to file>/reg.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line ;
try {
while((line =in.readLine()) != null) {
System.out.println(line);
}
} finally {
in.close();
}
ObjectMapper mapper = new ObjectMapper();
try {
Cheque cheque = mapper.readValue(line, Cheque.class);
System.out.println("Java object :");
System.out.println(cheque);
}
catch (JsonGenerationException ex) {
ex.printStackTrace();
}
catch (JsonMappingException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}}}
我得到的JSON响应是:
{
"bankName": [
"Bank"
],
"accountNumber": [
"989898989898"
],
"ifsCode": [
"0000000"
],
"micr": [
"0000000"
],
"payeeName": [
"name"
]
}
运行该程序后,我得到了预期的JSON响应,但是在将其转换为Java对象时,它在主线程中显示了nullPointerException。帮助我找出错误所在。
答案 0 :(得分:1)
在打印时,您在这里消耗/耗尽所有过程输入流:
try {
while((line =in.readLine()) != null) {
System.out.println(line);
}
后来,当您调用下面的内容时,它已经是null了:
Cheque cheque = mapper.readValue(line, Cheque.class);
您必须在上述while循环中对其进行处理,而不是仅将其打印出来
答案 1 :(得分:0)
当您到达该语句时:
Cheque cheque = mapper.readValue(line, Cheque.class);
变量line
为空。
因此,您可以重建JSON字符串(使用StringBuilder),或者删除打印响应的代码,然后直接从p.getInputStream()
解析JSON。
答案 2 :(得分:-1)
您的Java对象具有String值,但是JSON具有数组类型([]]