java.lang.string не может быть преобразован в jsonobject
Всем привет,
Я пытаюсь использовать службу WCF в клиенте android, но получаю следующую ошибку :
java.lang.string cannot be converted to jsonobject
вот мой код :
Андроид :
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; } }
ФОС :
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; } } }
Веб.конфиг :
<?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>
Помоги мне избавиться от этого.
Теперь я решил эту проблему, но я не получаю ни ошибки, ни вывода !!
Sandeep Mewara
Вы не поделились строкой, которую не удалось преобразовать. Трассировка стека ошибок должна совместно использовать "значение", которое не удается преобразовать.
[no name]
JSONObject s = новый JSONObject(новая строка(буфер));
Sandeep Mewara
А это что такое? Вы делитесь строкой кода, когда я спросил вас о полном сообщении трассировки стека.
[no name]
Я не печатаю сообщение в гонке стека.! Смотрите код!