com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为 BEGIN_OBJECT 但为 STRING

Posted

技术标签:

【中文标题】com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为 BEGIN_OBJECT 但为 STRING【英文标题】:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING 【发布时间】:2015-11-06 02:03:43 【问题描述】:
 package com.myapp.app;

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;

    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;
    import com.myapp.app.dataaccess.DatabaseHelper;
    import com.myapp.app.dataobjects.MediaMO;
    import com.myapp.app.dataobjects.UserMO;
    import com.myapp.app.delegates.MediaDelegates;
    import com.myapp.app.delegates.UserDelegate;
    import com.myapp.app.utility.Constants;

    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;



    public class ImageUploadActivity extends Activity 
        private static int RESULT_LOAD_IMAGE = 1;
        //EditText initialized here
        EditText Myusername;
        EditText user;
        private MediaDelegates mediaDelegates = new MediaDelegates();
        private File imgFile;
        private DatabaseHelper dbHelper;
        private Context context;
        private UserMO userMO = new UserMO();
        private ImageView imageView;
        private EditText eText;
        private Gson gson = new Gson();
        private ProgressDialog prgDialog;
        private MediaMO mediaMO = new MediaMO();
        private UserDelegate userDelegates = new UserDelegate();
        private String text;


        @Override
        public boolean onCreateOptionsMenu(Menu menu) 
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.image_upload, menu);

            return true;
        

        /**
         * Called when the activity is first created.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) 
            super.onCreate(savedInstanceState);
            setContentView(R.layout.imageupload);
            context = getApplicationContext();
            dbHelper = new DatabaseHelper(context);
            userMO = dbHelper.getRingeeUserData(1);
            imageView = (ImageView) findViewById(R.id.imgView);
            prgDialog = new ProgressDialog(this);
            // Set Progress Dialog Text
            prgDialog.setMessage("Please wait...");
            // Set Cancelable as False
            prgDialog.setCancelable(false);

            prgDialog.show();

            new AsyncTask<Void, Void, Bitmap>() 
                @Override
                protected Bitmap doInBackground(Void... arg0) 
                    String mediaMo = mediaDelegates.getFileFromServer(userMO, context);
                    if (!mediaMo.equals("null")) 
                        mediaMO = gson.fromJson(mediaMo, new TypeToken<MediaMO>() 
                        .getType());
                        try 
                            URL url = new URL(mediaMO.getFileSrcLink());
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                            connection.setDoInput(true);
                            connection.connect();
                            InputStream input = connection.getInputStream();
                            return BitmapFactory.decodeStream(input);
                         catch (IOException e) 
                            Log.i(Constants.TAG, e.toString());
                        
                     else
                        mediaMO = null;
                    Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_user);
                    return largeIcon;
                

     @Override
            protected void onPostExecute(Bitmap myBitmap) 
                prgDialog.cancel();
                imageView.setImageBitmap(myBitmap);
            
        .execute(null, null, null);

        //EditText added here for get current username

        Myusername = (EditText) findViewById(R.id.userEditText);
        String s = userMO.getUserName();
        Myusername.setText(s);

        Myusername.setOnClickListener(new View.OnClickListener() 

            public void onClick(View v) 
                final String str1 = Myusername.getText().toString();

                Intent int1 = new Intent(ImageUploadActivity.this, NameUpdateActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("userdata1", str1);
                int1.putExtras(bundle);
                //(int1);
                startActivityForResult(int1, 0);
            


        );

        Button buttonAddImage = (Button) findViewById(R.id.buttonAddPicture);
        buttonAddImage.setOnClickListener(new View.OnClickListener() 

            @Override
            public void onClick(View view) 
                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // Start the Intent
                startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);

            
        );

        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() 

            @Override
            public void onClick(View arg0) 
//                prgDialog.show();
                if (mediaMO == null) 
                    new AsyncTask<Void, Void, Bitmap>() 
                        @Override
                        protected Bitmap doInBackground(Void... arg0) 
                            MediaMO mediaMO1 = new MediaMO();
                            mediaMO1.setRingeeUserId(userMO.getRingeeUserId());
                            mediaMO1.setIsType(Constants.IS_TYPE_PROFILE_IMAGE);
                            String mediaMo = mediaDelegates.uploadFileToServer(mediaMO1, context, imgFile);
                            if (!mediaMo.equals("null")) 
                                mediaMO = gson.fromJson(mediaMo, new TypeToken<MediaMO>() 
                                .getType());
                                try 
                                    URL url = new URL(mediaMO.getFileSrcLink());
                                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                    connection.setDoInput(true);
                                    connection.connect();
                                    InputStream input = connection.getInputStream();
                                    return BitmapFactory.decodeStream(input);
                                 catch (IOException e) 
                                    Log.i(Constants.TAG, e.toString());
                                
                            
                            Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_user);
                            return largeIcon;
                        

                        @Override
                        protected void onPostExecute(Bitmap myBitmap) 
                            prgDialog.cancel();
                            imageView.setImageBitmap(myBitmap);
                        
                    .execute(null, null, null);
                 else 
                    new AsyncTask<Void, Void, Bitmap>() 
                        @Override
                        protected Bitmap doInBackground(Void... arg0) 
                            String mediaMo = mediaDelegates.updateFileToServer(mediaMO, context, imgFile);
                            if (!mediaMo.equals("null")) 
                                mediaMO = gson.fromJson(mediaMo, new TypeToken<MediaMO>() 
                                .getType());
                                try 
                                    URL url = new URL(mediaMO.getFileSrcLink());
                                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                    connection.setDoInput(true);
                                    connection.connect();
                                    InputStream input = connection.getInputStream();
                                    return BitmapFactory.decodeStream(input);
                                 catch (IOException e) 
                                    Log.i(Constants.TAG, e.toString());
                                
                            
                            Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_user);
                            return largeIcon;
                        

                        @Override
                        protected void onPostExecute(Bitmap myBitmap) 
                            prgDialog.cancel();
                            imageView.setImageBitmap(myBitmap);
                        
                    .execute(null, null, null);
                
            
        );
    

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) 

            Uri selectedImage = data.getData();
            String[] filePathColumn = MediaStore.Images.Media.DATA;

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            imgFile = new File(picturePath);

        
    


这是我收到“java.lang.RuntimeException:An error occurred while execution doInBackground()”的代码。我是android的新手。我不明白为什么会出现这个错误,任何人帮助我如何解决这个错误。

my logcat is

 08-13 13:31:22.520  18138-18255/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #5
        java.lang.RuntimeException: An error occured while executing doInBackground()
                at android.os.AsyncTask$3.done(AsyncTask.java:299)
                at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
                at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
                at java.util.concurrent.FutureTask.run(FutureTask.java:239)
                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
                at java.lang.Thread.run(Thread.java:838)
         Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)
                at com.google.gson.Gson.fromJson(Gson.java:810)
                at com.google.gson.Gson.fromJson(Gson.java:775)
                at com.google.gson.Gson.fromJson(Gson.java:724)
                at com.ringee.app.ImageUploadActivity$4$2.doInBackground(ImageUploadActivity.java:197)
                at com.ringee.app.ImageUploadActivity$4$2.doInBackground(ImageUploadActivity.java:192)
                at android.os.AsyncTask$2.call(AsyncTask.java:287)
                at java.util.concurrent.FutureTask.run(FutureTask.java:234)
                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
                at java.lang.Thread.run(Thread.java:838)
         Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
                at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:387)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:189)
                at com.google.gson.Gson.fromJson(Gson.java:810)
                at com.google.gson.Gson.fromJson(Gson.java:775)
                at com.google.gson.Gson.fromJson(Gson.java:724)
                at com.ringee.app.ImageUploadActivity$4$2.doInBackground(ImageUploadActivity.java:197)
                at com.ringee.app.ImageUploadActivity$4$2.doInBackground(ImageUploadActivity.java:192)
                at android.os.AsyncTask$2.call(AsyncTask.java:287)
                at java.util.concurrent.FutureTask.run(FutureTask.java:234)
                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
                at java.lang.Thread.run(Thread.java:838)

【问题讨论】:

***.com/questions/2190161/… 检查此问题以了解运行时异常 发布你的整个 logcat 您的最低 SDK 级别是多少? RuntimeException 不相关。细读“起因”部分真的太麻烦了吗? 引起:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 预期 BEGIN_OBJECT 但在第 1 行第 1 列路径 $" mediaMO = gson.fromJson(mediaMo, new TypeToken() .getType());"我在上面的代码中的这一行出现错误。如何解决这个问题 【参考方案1】:

在第 165 行,您是否尝试过仅传递您尝试转换的类而不是使用 TypeToken?

mediaMO = gson.fromJson(mediaMo, MediaMO.class);

而不是

mediaMO = gson.fromJson(mediaMo, new TypeToken<MediaMO>() .getType());

【讨论】:

以上是关于com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为 BEGIN_OBJECT 但为 STRING的主要内容,如果未能解决你的问题,请参考以下文章