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

时间:2016-12-28 10:25:02

标签: java json spring-mvc

我有一个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异常处的'{'开头。

2 个答案:

答案 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)

你正在使用retorfit发布@Mavericks吗?如果是,则使用compile' com.squareup.retrofit2:converter-scalars:2.1.0'用于发布纯文本。