rajeshlawrance
rajeshlawrance

Reputation: 559

org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

Here I want to display the JSON content using API key. But I am unable to get the authentication.

I am getting the error in JsonObject:

org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONObject

In my android application, I just pass the API key and URL id to get the JSON response in the following URL. I display the JSON content using JSON array.

But if I:

public class AndroidAPiActivity extends Activity {

/*
 * FlickrQuery = FlickrQuery_url
 * + FlickrQuery_per_page
 * + FlickrQuery_nojsoncallback
 * + FlickrQuery_format
 * + FlickrQuery_tag + q
 * + FlickrQuery_key + FlickrApiKey
 */

String FlickrQuery_url = "http://192.138.11.9/api/interests/";
String FlickrQuery_per_page = "&per_page=1";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";

// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
   String FlickrApiKey = "f65215602df8f8af";

   EditText searchText;
   Button searchButton;
   TextView textQueryResult, textJsonResult;
   ImageView imageFlickrPhoto;
   Bitmap bmFlickr;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       searchText = (EditText)findViewById(R.id.searchtext);
       searchButton = (Button)findViewById(R.id.searchbutton);
       textQueryResult = (TextView)findViewById(R.id.queryresult);
       textJsonResult = (TextView)findViewById(R.id.jsonresult);
       imageFlickrPhoto = (ImageView)findViewById(R.id.flickrPhoto);
       searchButton.setOnClickListener(searchButtonOnClickListener);
   }

   private Button.OnClickListener searchButtonOnClickListener
   = new Button.OnClickListener(){

 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  String searchQ = searchText.getText().toString();
  String searchResult = QueryFlickr(searchQ);
  textQueryResult.setText(searchResult);
  String jsonResult = ParseJSON(searchResult);
  textJsonResult.setText(jsonResult);

  if (bmFlickr != null){
   imageFlickrPhoto.setImageBitmap(bmFlickr);
  }
 }};

   private String QueryFlickr(String q){

    String qResult = null;

    String qString =
      FlickrQuery_url
      + FlickrQuery_per_page
      + FlickrQuery_nojsoncallback
      + FlickrQuery_format
      + FlickrQuery_tag + q 
      + FlickrQuery_key + FlickrApiKey;

    HttpClient httpClient = new DefaultHttpClient();
       HttpGet httpGet = new HttpGet(qString);

       try {
  HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();

  if (httpEntity != null){
   InputStream inputStream = httpEntity.getContent();
   Reader in = new InputStreamReader(inputStream);
   BufferedReader bufferedreader = new BufferedReader(in);
   StringBuilder stringBuilder = new StringBuilder();

   String stringReadLine = null;

   while ((stringReadLine = bufferedreader.readLine()) != null) {
    stringBuilder.append(stringReadLine + "\n");
    }

   qResult = stringBuilder.toString();

  }

 } catch (ClientProtocolException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {  
  // TODO Auto-generated catch block
  e.printStackTrace();
 }

       return qResult;
   }

   private String ParseJSON(String json){

    String jResult = null;
    bmFlickr = null;
    String key_id;
    String category;
    String subcategory;
    String title;
    String icon_image;

    try
     {
  JSONObject JsonObject = new JSONObject(json);
  JSONObject Json_photos = JsonObject.getJSONObject("interests");
  JSONArray JsonArray_photo = Json_photos.getJSONArray("interest");

  //We have only one photo in this exercise
  JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(0);

  key_id = FlickrPhoto.getString("row_key");
  category = FlickrPhoto.getString("category");
  subcategory = FlickrPhoto.getString("subcategory");
   title = FlickrPhoto.getString("title");

  jResult = "\n key_id: " + key_id + "\n"
    + "category: " + category + "\n"
    + "subcategory: " + subcategory + "\n"
    + "title: " + title + "\n";

  bmFlickr = LoadPhotoFromFlickr(key_id, category, subcategory,title);

 } catch (JSONException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }

    return jResult;
   }

   private Bitmap LoadPhotoFromFlickr(
     String key_id, String category, String subcategory,
     String title){
    Bitmap bm= null;

    String icon_image = null;
 //   String FlickrPhotoPath ="";
   String FlickrPhotoPath ="http://182.72.180.34/media/"+icon_image+".jpg";

    URL FlickrPhotoUrl = null;

    try {

  FlickrPhotoUrl = new URL(FlickrPhotoPath);

  HttpURLConnection httpConnection = (HttpURLConnection) FlickrPhotoUrl.openConnection();
  httpConnection.setDoInput(true);
  httpConnection.connect();
  InputStream inputStream = httpConnection.getInputStream();
  bm = BitmapFactory.decodeStream(inputStream);

 } catch (MalformedURLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }

    return bm;
   }
}

Upvotes: 11

Views: 58913

Answers (7)

BasketCase
BasketCase

Reputation: 1

HOW I FIXED THE FOLLOWING ERRORS:

=============================================================================

org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

org.json.JSONException: Value permissions of type java.lang.String cannot be converted to JSONObject

==============================================================================

This might not apply to this particular scenario, but it comes up as a top search result for the given issue/keyword.

So, i bought a script from a professional vendor on codecanyon.

The script consisted of 3x main parts; - MAIN CART SITE (PHP) - MAIN ADMIN SITE + /API (PHP) - ANDROID ADMIN APP (JAVA)

I found many issues once the script was installed. Ranging from incomplete or missing table arrays on the MAIN CART SITE, then i had a problem on the ANDROID ADMIN APP that (upon inspection of logs) revealed a mysqli_exception was to blame.

So after hours of messing around with loops and trying to figure out where the issue was. After actually learning how to dump output to the logs / logcat. I was able to determine that it was in actual fact, a;

BREAKING CHANGE SINCE MYSQL-8


TO FIX, RUN THE FOLLOWING COMMANDS IN mysql TERMINAL;

  SET GLOBAL sql_mode = '';
  SET SESSION sql_mode = '';

THIS REMOVES THE 'STRICT MODE' amongst other rules that has caused me so much grief over the last few days. Thought i'd better share the answer, hopefully save someone else days of eye-drying torment =].

Remember to reintroduce the default ruleset one rule at a time and test to see what modes your app can support (if this solution fixes your problem) as they are no doubt essential security/data-integrity measures that are there for good reason. Ideally, update codebase to comply with current standards. Unfortunately that's way beyond me at this stage.

Hope this works for you guys.

Upvotes: 0

Mahmoud Ayman
Mahmoud Ayman

Reputation: 1324

I've faced this issue too, I changed my Internet connection to another network and it works.

The problem was that ISP doesn't accept http access.

Another solution you can open VPN and try again, and maybe it works...

Upvotes: 0

Shubham Kumar Gupta
Shubham Kumar Gupta

Reputation: 1147

May be this can help

https://teamtreehouse.com/community/solved-exception-cannot-convert-string-type-to-json-object

Solved.

It turns out the runtime error stretched back to the previous video.

I was doing

JSONObject currently = new JSONObject("currently"); instead of

JSONObject currently = forecast.getJSONObject("currently");

So my guess is Android thought I was trying to setup an entirely new JSON object instead of trying to retrieve information from an existing one! :) Now the console displays the time perfectly!

Upvotes: 0

Ashish Tanna
Ashish Tanna

Reputation: 677

I received the same "<!Doctype..." error when working with Google Translate's json URLs. Then, I found this code somewhere and it worked :

        BasicHttpParams basicHttpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout((HttpParams)basicHttpParams, (int)10000);
        HttpConnectionParams.setSoTimeout((HttpParams)basicHttpParams, (int)10000);
        HttpConnectionParams.setTcpNoDelay((HttpParams)basicHttpParams, (boolean)true);
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient((HttpParams)basicHttpParams);
        HttpGet httpGet = new HttpGet(url);
        BasicResponseHandler basicResponseHandler = new BasicResponseHandler();

        JSONObject json=null;
        try {
            json = new JSONObject((String)defaultHttpClient.execute((HttpUriRequest)httpGet, (ResponseHandler)basicResponseHandler));
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Upvotes: -1

Sravani
Sravani

Reputation: 528

Yes, we get such kind of warning when the given URL is not valid.

Just check the URL once.

Upvotes: 5

Mr.India
Mr.India

Reputation: 674

Remove docType from API. and set content Type Application/json . (as text/html will not read as json . thus you were seeing the error.)

Upvotes: 0

Richard Le Mesurier
Richard Le Mesurier

Reputation: 29722

Update:

Based on the HTML response, I can tell you that this is not JSON. The response tells me that you have the incorrect URL for your web service.

You need to check your URL.

Extra Info / Previous Answer:

It looks like the simple answer is the right one - your result is not a valid JSON string. See JSON.org website for details on what JSON should look like.

Check out JSON Parser Online - I find its very useful when working with JSON.

It is strange that you are requesting JSON, and it is not returning it properly - perhaps I have missed something.

Upvotes: 14

Related Questions