代码适用于个人电脑,但不适用于Android(Gson)

代码适用于个人电脑,但不适用于Android(Gson)

问题描述:

我没有把我的电脑上的代码移到Android上的好运气。我的代码在我的电脑上运行,但在我的Android手机上运行时遇到问题。我正在使用相同的库(GSON),我所做的一切都不应该是Android设备的问题。有人能帮我吗?代码适用于个人电脑,但不适用于Android(Gson)

的logcat:

08-10 22:39:22.400: E/AndroidRuntime(29153): FATAL EXCEPTION: AsyncTask #1 
08-10 22:39:22.400: E/AndroidRuntime(29153): java.lang.RuntimeException: An error occured while executing doInBackground() 
08-10 22:39:22.400: E/AndroidRuntime(29153): at android.os.AsyncTask$3.done(AsyncTask.java:278) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.lang.Thread.run(Thread.java:856) 
08-10 22:39:22.400: E/AndroidRuntime(29153): Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.Gson.fromJson(Gson.java:806) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.Gson.fromJson(Gson.java:761) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.Gson.fromJson(Gson.java:710) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.g4apps.json.android.verification.client.JsonVerificationClass.jsonVerificationCall(JsonVerificationClass.java:73) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.g4apps.json.android.verification.client.MainActivity$SmpProcessor.doInBackground(MainActivity.java:45) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.g4apps.json.android.verification.client.MainActivity$SmpProcessor.doInBackground(MainActivity.java:1) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at android.os.AsyncTask$2.call(AsyncTask.java:264) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
08-10 22:39:22.400: E/AndroidRuntime(29153): ... 5 more 
08-10 22:39:22.400: E/AndroidRuntime(29153): Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.stream.JsonReader.nextString(JsonReader.java:464) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:349) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:337) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.Gson.fromJson(Gson.java:795) 
08-10 22:39:22.400: E/AndroidRuntime(29153): ... 12 more 

我的类:

package com.g4apps.json.android.verification.client; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.net.URI; 
import java.util.ArrayList; 
import java.util.List; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 

import com.google.gson.*; 
import com.google.gson.reflect.TypeToken; 



// The Return class defines the structure of the json object returned by the web service 
public class JsonVerificationClass { 

    public static class VerificationData { 
     private String Name; 
     private String Phone; 

     public VerificationData (String name, String smartphone){ 
      this.Name=name; 
      this.Phone=smartphone; 
     } 

     public String getName() { return Name; } 

     public String getSmartPhone() { return Phone; } 
    } 

    // jsonCall is the actual call to the webservice 
    public static String jsonVerificationCall(URI url, String app, VerificationData data) { 


     try { 
      //We need to json objects. One for the request and one for the response 
      //The request object is simple and doesn't require an object class to define it. 
      Gson json = new Gson(); 
      String jsondata= json.toJson(data); 

      // We use the same HttpClient and HttpPost commands in both the PC and Android versions. 
      // These libraries are included in the Android SDK but must be added for the PC. 
      HttpClient client = new DefaultHttpClient(); 
      HttpPost post2 = new HttpPost(url); 

      // We use list to List to make the Post Entities 
      List<NameValuePair> namevaluePairs = new ArrayList<NameValuePair>(1); 
      namevaluePairs.add(new BasicNameValuePair("app",app)); 
      namevaluePairs.add(new BasicNameValuePair("data",jsondata.toString())); 
      //System.out.println(namevaluePairs.toString()); 
      post2.setEntity(new UrlEncodedFormEntity(namevaluePairs)); 
      HttpResponse response = client.execute(post2); 

      //Read in the response and rebuild the json string 
      BufferedReader rd= new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
      StringBuilder myresponse = new StringBuilder(); 
      String inputline; 
      while((inputline = rd.readLine()) !=null) myresponse.append(inputline); 

      //Get the type from Return Object so we can remove it from the Json String 
      java.lang.reflect.Type StringType = new TypeToken<String>(){}.getType(); 
      rd.close(); 
      //System.out.println(myresponse.toString()); 
      String return2= new Gson().fromJson(myresponse.toString(), StringType); 
      return return2; 
     } 
     catch (UnsupportedEncodingException uee) { 
      uee.printStackTrace(); 
     } 
     catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return null; 
    } 

} 

我的活动:

package com.g4apps.json.android.verification.client; 

import java.net.URI; 
import java.net.URISyntaxException; 

import com.g4apps.json.android.verification.client.JsonVerificationClass; 
import com.g4apps.json.android.verification.client.JsonVerificationClass.VerificationData; 

import android.os.AsyncTask; 
import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.widget.TextView; 


public class MainActivity extends Activity { 
    private TextView tv; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     tv = (TextView)findViewById(R.id.TextView01); 


     //Start new task and run SmpProcessor (Android 2.3+ prohibits Networking activities from running in main thread. 
     SmpProcessor task = new SmpProcessor(); 
     task.execute(); 

    } 
    // added asynctask though other thread methods can be used 
    private class SmpProcessor extends AsyncTask <Void,Void,String> { 

      // doInBackground sets up variables and calls jsonCall. multiple to jsoncall can be made from the same thread. 
      @Override 
      protected String doInBackground(Void... voids){ //String[] doInBackground(Void... voids){ 

       try { 

        URI url = new URI("http://myservice.com/webservices.php"); 
        String app="verify"; 
        VerificationData data = new VerificationData("Sam","9055551212"); 

        // Make jsonCall with will return Return Object 
        String result = JsonVerificationClass.jsonVerificationCall(url,app,data); 


        return result; 
       } catch (URISyntaxException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       //return null; 
       return null; 
      } 
      // Handled the retrieval of the data in onPostExecute so I could output it to the android device through the MainActivity. 
      protected void onPostExecute(String result) { 


       tv.setText("Response: " + result); 


       // Handle or call processing for data here as it needs to be done post html call. 
      } 
     } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 


} 
+1

请同时发布产生此错误的最小json文件。 – 2012-08-11 06:13:43

+0

啊,发现错误。服务器为错误响应返回不同的格式。不知道为什么我得到错误响应,但因为生成消息的代码应该是正确的。 – Codeguy007 2012-08-11 11:37:50

对不起,我想我叫错服务,它返回一个错误消息与客户预期的格式不同。

它期待{ “字符串”},并获得{ “状态”: “字符串”, “数据”: “的String []”}

感谢德克谁的建议,看看JSON字符串透露回答。

+0

所以你可以将你的答案标记为解决答案。因为如果你不这样做你的问题将在未解决的问题。 – Hosein 2012-08-11 11:52:54

+0

你知道我无法接受我自己的答案。 – Codeguy007 2012-08-11 12:11:11

+0

我想你可以。这有一个选项。 – Hosein 2012-08-11 12:12:53