Mavericks
Mavericks

Reputation: 283

JSONException: A JSONObject text must begin with '{' at character

I have a JSON object as below. When I try to fetch the value of name using :

String name = jsonObject.getJSONObject("result").getString("name");

In 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": ""
        } 
    } 
}

It gives me:

org.json.JSONException: A JSONObject text must begin with '{' at character 6 exception.

Upvotes: 2

Views: 1996

Answers (2)

Itay Maman
Itay Maman

Reputation: 30733

I believe you somehow did not load the right content. Here's a small program that consumes the input that you posted:

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); 
  }
}

The output is, as expected:

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"}}

Therefore, I think you have problems in loading/initializing the object pointed by the jsonObject variable.

FTR, I am using the JSON library from https://github.com/stleary/JSON-java.

Upvotes: 1

Piyush Patel
Piyush Patel

Reputation: 381

@Mavericks are you posting using retorfit? if yes then use compile 'com.squareup.retrofit2:converter-scalars:2.1.0' for posting plain text.

Upvotes: 0

Related Questions