当前位置: 首页 > 知识库问答 >
问题:

JSONException:JSONObject文本必须以字符“{”开头

桓深
2023-03-14
String name = jsonObject.getJSONObject("result").getString("name");
{ 
    "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": ""
        } 
    } 
}

JSONException:JSONObject文本必须以字符6处的{开头。

共有1个答案

施辉
2023-03-14

我相信你不知何故没有加载正确的内容。下面是一个小程序,它消耗您发布的输入:

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变量指向的对象方面存在问题。

 类似资料: