Click here to Skip to main content
11,932,780 members (50,517 online)
Rate this:
Please Sign up or sign in to vote.
See more: Mobile WCF Android
Hello all,

I'm trying to consume WCF service in android client but I'm getting following error :
java.lang.string cannot be converted to jsonobject

here is my code :

Android :
package com.example.studentsapp;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import android.view.View.OnClickListener;
public class MainActivity extends Activity 
	private final static String srvc_uri = "";
	private EditText idTxt;
	private Button btn;
	private TextView tv;
    protected void onCreate(Bundle savedInstanceState) 
        idTxt = (EditText) findViewById(;
        btn = (Button) findViewById(;
        btn.setOnClickListener(new OnClickListener() 
			public void onClick(View v) 
				// TODO Auto-generated method stub
					DefaultHttpClient client = new DefaultHttpClient();
			    	// http get request
			    	HttpGet request = new HttpGet(srvc_uri + idTxt.getText());
			    	// set the hedear to get the data in JSON format
			    	request.setHeader("Accept", "application/json");
			        request.setHeader("Content-type", "application/json");
			        //get the response
			        HttpResponse response = client.execute(request);
			        HttpEntity entity = response.getEntity();
			        //if entity contect lenght 0, means no students exist in the system with these code
			        if(entity.getContentLength() != 0) 
			        	// stream reader object
			        	Reader reader = new InputStreamReader(response.getEntity().getContent());
				        //create a buffer to fill if from reader
			        	char[] buffer = new char[(int) response.getEntity().getContentLength()];
				        //fill the buffer by the help of reader
				        //close the reader streams
			        	//for the student json object
				        JSONObject s =  new JSONObject(new String(buffer));
				        //Toast.makeText(getApplicationContext(), s.getString("StudentName"), Toast.LENGTH_LONG).show();
				catch(Exception ex)
						Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
    public boolean onCreateOptionsMenu(Menu menu) 
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace StudentWcfServiceforAndroid
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    public interface IService1
        string GetData(int value);
        CompositeType GetDataUsingDataContract(CompositeType composite);
        // TODO: Add your service operations here

    public interface IstudentInfo 
        [WebGet(UriTemplate = "GetName/{id}",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]
        Student GetStudentName(int studentID);
    public class StudentInfo : IstudentInfo 
        public Student GetStudentName(int studentID)
            Student studs = GetStuds().Where(s => s.StudentID == studentID).FirstOrDefault();
            return studs;
        private List<Student> GetStuds()
            return new List<Student>
                new Student
                {StudentID=1, StudentName="AAA"},
                new Student
                {StudentID=2, StudentName="BBB"}
    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    public class CompositeType
        bool boolValue = true;
        string stringValue = "Hello ";
        public bool BoolValue
            get { return boolValue; }
            set { boolValue = value; }
        public string StringValue
            get { return stringValue; }
            set { stringValue = value; }
    public class Student
        public int StudentID
        { get; set; }
        public string StudentName
        { get; set; }

Web.config :
<?xml version="1.0"?>
    <compilation debug="true" targetFramework="4.0" />
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
        <standardEndpoint helpEnabled="true" automaticFormatSelectionEnabled="true" />
      <service name="StudentWcfServiceforAndroid.StudentInfo">
        <endpoint kind="webHttpEndpoint" contract="StudentWcfServiceforAndroid.IStudentInfo" />
    <modules runAllManagedModulesForAllRequests="true"/>

Help me to get rid of this.

Now I've solved this problem but I'm neither getting any error nor output !!
Posted 2-Feb-13 22:45pm
Edited 5-Feb-13 19:30pm
Sandeep Mewara 3-Feb-13 4:14am
You have not shared the string that failed to convert. Error stack trace must be sharing the 'value' that fails conversion.
Krunal Rohit 3-Feb-13 4:40am
JSONObject s = new JSONObject(new String(buffer));
Sandeep Mewara 3-Feb-13 4:54am
What's this? You are sharing a line of code when I asked you the full stack trace message.
Krunal Rohit 3-Feb-13 5:03am
I'm not printing message in stack race.! See code!

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Maybe I'm missing something but shouldn't the line be

JSONObject s =  new JSONObject(buffer);

Krunal Rohit 7-Feb-13 4:56am
Let me see if it could help !!
Krunal Rohit 7-Feb-13 4:57am
Error !!!!
Darren_vms 8-Feb-13 10:41am
ok I tried, good luck

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web03 | 2.8.151126.1 | Last Updated 7 Feb 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100