3

I need to upload an image from my android application by calling restful webservice in c#,But when i try it by adding byte[] to JSONObject,it converts the byte[] to string and the c# service throws Bad request("Error deserializing the Object.Element from namespace '' expected.Found text'[B@22b6cc7f'.

Android Code:
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ttulips);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    bitMapData = stream.toByteArray();

            JSONObject jsonParam = new JSONObject();
            try {
            jsonParam.put("IncomingFile",bitMapData);               
            jsonParam.put("FileName", "name.jpg");

            Log.d("Json",jsonParam+"");
} catch (JSONException e) {
            e.printStackTrace();
        }

The log of JSON request is coming as {"IncomingFile":"[B@22b67f","FileName":"name.jpg"}

Even tried converting the byte array to Base64 encoded byte array,but while adding base64 byte array to jsonobject,it is taken as string.

How should I solve this issue?Thanks in advance.

3
  • What is wrong with a Base64 encoded string? This should be your choice Commented Aug 17, 2016 at 7:10
  • JSON only supports limited value types (strings, numbers, booleans and null). So you'll somehow have to convert the byte array to a string and deserialize accordingly Commented Aug 17, 2016 at 7:12
  • Thank you for your response.My c# service is expecting byte[].So is there any option to send byte[] instead of String?Otherwise the service need to be changed? Commented Aug 17, 2016 at 7:35

4 Answers 4

1

try this convert bitmap to string and pass this string to c# server

 if(fileUri1 != null) {
                bitmap1 = BitmapFactory.decodeFile(fileUri1.getPath(),
                        options);
                ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
                if(bitmap1 != null) {
                    bitmap1.compress(Bitmap.CompressFormat.PNG, 50, baos1);
                    byte[] b1 = baos1.toByteArray();
                    bitmapstring1 = Base64.encodeToString(b1, 

                    Base64.DEFAULT);
                }
            }

webservice call:

 public class CallWebService extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        // Call Webservice for Get Menus
        WebServiceCall webServiceCall = new WebServiceCall(); // Custom class for call webservice
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;


        parameters = new ArrayList<NameValuePair>();

        parameters.add(new BasicNameValuePair("Name",uname12));
        parameters.add(new BasicNameValuePair("Address", uaddr12));
        parameters.add(new BasicNameValuePair("Email", en));
        parameters.add(new BasicNameValuePair("Qualification", uquali12));
        parameters.add(new BasicNameValuePair("Phoneno", ucontactno12));
        parameters.add(new BasicNameValuePair("Appliedfor", uappfor12));
        parameters.add(new BasicNameValuePair("Image", bitmapstring));
        parameters.add(new BasicNameValuePair("Resumeimage", bitmapstring1));
        parameters.add(new BasicNameValuePair("Operation", "i"));
        Log.i("param::",parameters.toString());
        response = webServiceCall.makeServiceCall(mUrlWebServiceLogin, parameters);


        Log.d("ResponseLogin:", response);



        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        if (progressDialog.isShowing())
            progressDialog.dismiss();

        if(response.contains("\"success\"")){
            session.createLoginSession(uname12);
            Toast.makeText(getApplicationContext(),"Successfully inserted",Toast.LENGTH_SHORT).show();
            Intent in = new Intent(getApplicationContext(),InterView.class);
            in.putExtra("Name",uname12);

            startActivity(in);
            finish();


        }else{
            Toast.makeText(getApplicationContext(),"data not inserted",Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();
        progressDialog.setCanceledOnTouchOutside(false);
        super.onPreExecute();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use Base64 on both sides, actually converting byte[] to String isn't the main problem read here

Comments

0

Try below for creating JSON:

 String json = "{\"IncomingFile\":\""+ new String(bytesEncoded) +"\",\"FileName\":\""+name.jpg+"\"}";

Where bytesEncoded should be Base64 encoded image.

Hope it helps!

2 Comments

Thank you for the solution.I tried this solution and its showing invalid character '.'.Should the service be expecting byte array or String?
remove '.' from the json, and yes service should be expecting String only, as how can you pass bytes in json, eventually it's gonna be string right?
-1

here the object bitMapData is a bytearray and must be converted to String then you must use in the Json Object jsonParam.put("IncomingFile",new String(bitMapData));

2 Comments

No need for a JSON array here ... a byte array fits very well into a single string
a small missunderstanding bro.. ur correct @devnull69

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.