Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 java.io.InputStreamReader;
import java.io.Reader;

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.app.Activity;
import android.view.*;
import android.widget.*;
import android.view.View.OnClickListener;

public class MainActivity extends Activity 
{
	private final static String srvc_uri = "http://101.63.53.242/StudentWcfServiceforAndroid/service1.svc/GetName/";
	private EditText idTxt;
	private Button btn;
	private TextView tv;
	

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        idTxt = (EditText) findViewById(R.id.editText1);
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() 
        {
			@Override
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				try
				{
					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
			        	reader.read(buffer);
				        //close the reader streams
			        	reader.close();

			        	//for the student json object
				        JSONObject s =  new JSONObject(new String(buffer));
				        
				        //Toast.makeText(getApplicationContext(), s.getString("StudentName"), Toast.LENGTH_LONG).show();
				        tv.setText(s.getString("StudentName"));
			        }  
				}
				catch(Exception ex)
				{
						Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
				}
			}
		});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
}


WCF :
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.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here

    }

    [ServiceContract]
    public interface IstudentInfo 
    {
        [OperationContract]
        [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.
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }

    [DataContract]
    public class Student
    {
        public int StudentID
        { get; set; }

        public string StudentName
        { get; set; }
    }

}


Web.config :
XML
<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- 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"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint helpEnabled="true" automaticFormatSelectionEnabled="true" />
      </webHttpEndpoint>
    </standardEndpoints>
    <services>
      <service name="StudentWcfServiceforAndroid.StudentInfo">
        <endpoint kind="webHttpEndpoint" contract="StudentWcfServiceforAndroid.IStudentInfo" />
      </service>
    </services>

  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>


Help me to get rid of this.

Now I've solved this problem but I'm neither getting any error nor output !!
Posted
Updated 15-Mar-18 7:20am
v3
Comments
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.
[no name] 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.
[no name] 3-Feb-13 5:03am    
I'm not printing message in stack race.! See code!

1 solution

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

Java
JSONObject s =  new JSONObject(buffer);


/Darren
 
Share this answer
 
Comments
[no name] 7-Feb-13 4:56am    
Let me see if it could help !!
[no name] 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900