我有一个JSON对象,如下所示。当我尝试使用以下方法获取name的值时:
String name = jsonObject.getJSONObject("result").getString("name");
在java中
{
"result":
{
"name": "ABC",
"dob": "12-11-1958",
"issue_date": "01-11-2011",
"blood_group": "",
"father/husband": "BCD",
"address": "53/9 ASHOK NAGAR,Delhi 110018",
"cov_details": {
"LMV": "01-11-2011 DY.DIR.ZONAL OFFICE,NORTH WEST DISTRICT-II,ROHINI",
"MCWG": "01-11-2011 DY.DIR.ZONAL OFFICE,NORTH WEST DISTRICT-II,ROHINI"
},
"validity": {
"non-transport": "01-11-1958 to 31-10-1978",
"transport": ""
}
}
}
它给了我:
org.json.JSONException:JSONObject文本必须以字符6异常处的'{'开头。
答案 0 :(得分:1)
我相信你不知道加载了正确的内容。这是一个消耗您发布的输入的小程序:
package org.json;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (Scanner sc = new Scanner(Main.class.getResourceAsStream("in.json")); sc.hasNext(); ) {
sb.append(sc.nextLine()).append("\n");
}
JSONObject jsonObject = new JSONObject(sb.toString());
String name = jsonObject.getJSONObject("result").getString("name");
System.out.println("name=" + name);
System.out.println("jsonObject=" + jsonObject);
}
}
正如预期的那样输出:
name=ABC
jsonObject={"result":{"cov_details":{"MCWG":"01-11-2011 DY.DIR.ZONAL OFFICE,NORTH WEST DISTRICT-II,ROHINI","LMV":"01-11-2011 DY.DIR.ZONAL OFFICE,NORTH WEST DISTRICT-II,ROHINI"},"address":"53/9 ASHOK NAGAR,Delhi 110018","issue_date":"01-11-2011","dob":"12-11-1958","name":"ABC","blood_group":"","validity":{"transport":"","non-transport":"01-11-1958 to 31-10-1978"},"father/husband":"BCD"}}
因此,我认为您在加载/初始化jsonObject
变量指向的对象时遇到问题。
FTR,我正在使用https://github.com/stleary/JSON-java中的JSON库。
答案 1 :(得分:0)