NAVIGATION - SEARCH

JSON Communication Between Android And Asp.Net C#

Building products across platforms is the new normal in today's ever changing technological environment. How do you communicate between an App in Android and a backend system built in Asp.Net C#? This article will explain a simple Json based approach to communicate between Android and Asp.Net C#. Json is a very simple yet powerful object notation structure which can be used to tranfer data across platforms. We will use Json serialization and see how easy it is to transmit data to and from Asp.Net and Android.

Let us first see the steps required or the architecture of this project. We are assuming you are well versed with both systems and know how to build basic applications using Android and Asp.Net and also how a virtual directory in IIS is created to host a page publicly.

Android

  • Download Gson 2.3.1 jar file and include in the libs folder
  • Create class objects to hold data
  • Create function to transmit or post data to Asp.Net endpoint
  • Write asynTask to finally send data and receive response

Asp.Net C#

  • Create aspx page to receive data
  • Create class objects to hold data
  • Create function to process data and send back response

We will build solution around a simple business use case where a user downloads the app and fills his/her user profile data. The app will send this data back to our Asp.Net backend system and completes the registration process. We will collect name, email, phone number, address details through our app.

Let's begin with the Android code assuming a sample app is built and Gson 2.3.1 jar file is setup.

Create a class object to hold this profile data. Here we have created 4 objects as shown below;

public class Data_Request
{
	public String TYPE;
	public String JSONDATA;
}

public class Data_Response
{
	public String STATUS;
	public String MESSAGE;
	public String JSONDATA;
}

public class objREGISTERATION
{
	public String NAME;
	public String EMAIL;
	public String PHONE;
	public String ADDRESS;
}

public class objREGISTERATION_DETAILS
{
	public String ACCOUNT_ID;
	public String ACCOUNT_TYPE;
}

Create function to transmit profile data to Asp.Net endpoint

public String HTTPRequest_PostJSON(String JSONDATA, String TYPE)
{
	String DATA = "";
	try
	{
		Gson gson = new Gson();
		Data_Request r = new Data_Request();
		r.TYPE = TYPE;
		r.JSONDATA = JSONDATA;
		
		JSONDATA = gson.toJson(r, Data_Request.class);
		
		URL url = new URL("http://myapp.example.com/processrequest.aspx");		//THIS IS SAMPLE ENDPOINT AND CAN BE ANYTHING
		HttpURLConnection connection = (HttpURLConnection)url.openConnection();
		connection.setRequestProperty("Accept", "application/json");
		connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
		connection.setRequestMethod("POST");
		connection.connect();

		OutputStream out = connection.getOutputStream();
		out.write(JSONDATA.getBytes("UTF-8"));
		out.flush();
		out.close();

		InputStream in = connection.getInputStream();
		if(in != null)
		{
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			String linedata = "";
			StringBuffer SB = new StringBuffer();
			while((linedata=reader.readLine())!=null)
			{
				SB.append(linedata);
			}
			reader.close();
			in.close();

			DATA = SB.toString();
		}
		else
			DATA = "Error - No data returned";

		connection.disconnect();
	}
	catch (Exception ex)
	{
		DATA = "Exception - " + ex.toString();
		android.util.Log.e("MyApp", ex.toString());
	}
	return DATA;
}

Finally, let's write an asyncTask to initiate communication and process response. We use asyncTask since we want to process data on a non-blocking thread.

private class asyncRegister extends AsyncTask<String, Void, String>
{
	@Override
	protected String doInBackground(String...params)
	{
		String ResponseData = "";
		try 
		{
			Gson gson = new Gson();
			objREGISTERATION u = new objREGISTERATION();
			u.NAME = params[0];
			u.EMAIL = params[1];
			u.PHONE = params[2];
			u.ADDRESS = params[3];
			String JSONDATA = gson.toJson(u, objREGISTERATION.class);
			ResponseData = HTTPRequest_PostJSON(JSONDATA, "RegisterUser");
		}
		catch (Exception ex) 
		{
			ResponseData = "Exception - " + ex.toString();
			android.util.Log.e("MyApp", ex.toString());
		}
		return ResponseData;
	}

	@Override
	protected void onPostExecute(String result)
	{			
		try
		{
			Gson gson = new Gson();
			Data_Response r = new Data_Response();
			r = gson.fromJson(result, Data_Response.class);
			if(r.STATUS.equalsIgnoreCase("success"))
			{
				objREGISTERATION_DETAILS d = new objREGISTERATION_DETAILS();
				d = gson.fromJson(r.JSONDATA, objREGISTERATION_DETAILS.class);
				String ACCOUNT_ID = d.ACCOUNT_ID;
				String ACCOUNT_TYPE = d.ACCOUNT_TYPE;
				
				//PROCESS DATA AS PER YOUR NEED
			}
			else
				android.util.Log.e("MyApp", r.MESSAGE);
		}
		catch (Exception ex)
		{				
			android.util.Log.e("MyApp", ex.toString());
		}
	}
}

Now comes the Asp.Net part

Create an aspx page with the name processrequest.aspx and open its code behind.

Create similar class object to hold data. Here we have created 4 objects as shown below;

public class Data_Request
{
	public String TYPE;
	public String JSONDATA;
}

public class Data_Response
{
	public String STATUS;
	public String MESSAGE;
	public String JSONDATA;
}

public class objREGISTERATION
{
	public String NAME;
	public String EMAIL;
	public String PHONE;
	public String ADDRESS;
}

public class objREGISTERATION_DETAILS
{
	public String ACCOUNT_ID;
	public String ACCOUNT_TYPE;
}

Let's write some code to read posted data. We will use the Page_Load function to do that

using System.IO;
using System.Text;
using System.Data;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;

protected void Page_Load(object sender, EventArgs e)
{
	JavaScriptSerializer serializer = new JavaScriptSerializer();
	Data_Response r = new Data_Response();
	
	try
	{
		Request.InputStream.Position = 0;
		StreamReader SR = new StreamReader(Request.InputStream);
		string JSONDATA = SR.ReadToEnd();
		if (JSONDATA.Length > 0)
		{
			
			Data_Request r = new Data_Request();
			r = serializer.Deserialize<Data_Request>(JSONDATA);
			string TYPE = r.TYPE;
			string JSONDATA = r.JSONDATA;
			switch (TYPE)
			{
				case "RegisterUser":
					objREGISTERATION u = new objREGISTERATION();						
					objREGISTERATION_DETAILS d = new objREGISTERATION_DETAILS();
					
					u = serializer.Deserialize<objREGISTERATION>(JSONDATA);

					string NAME = u.NAME;
					string EMAIL = u.EMAIL;
					string PHONE = u.PHONE;
					string ADDRESS = u.ADDRESS;
					
					//PROCESS THIS DATA AS PER YOUR NEED AND SEND THE RESPONSE BACK TO ANDROID APP
					
					d.ACCOUNT_ID = "12345";
					d.ACCOUNT_TYPE = "Consumer";
					
					r.STATUS = "success";
					r.MESSAGE = "success";
					r.JSONDATA = serializer.Serialize(d)
					
					PushResponse(serializer.Serialize(r));
					
					break;
		}
		else
		{
			r.STATUS = "error";
			r.MESSAGE = "error";
			r.JSONDATA = "";
			
			PushResponse(serializer.Serialize(r));
		}
	}
	catch (Exception ex)
	{
		r.STATUS = "exception";
		r.MESSAGE = "exception";
		r.JSONDATA = "";
		
		PushResponse(serializer.Serialize(r));
	}
}

private void PushResponse(string JSONDATA)
{
	HttpContext.Current.Response.ContentType = "application/json";
	HttpContext.Current.Response.Write(JSONDATA);
	HttpContext.Current.Response.Flush();
	HttpContext.Current.Response.SuppressContent = true;
	HttpContext.Current.ApplicationInstance.CompleteRequest();
}

The code described above is a simple structure which you can incorporate in your projects. Please modify it as per your need. We have tried to explain a basic communication channel between Android and Asp.Net C# using Json data. Please feel free to write below in comments section or use the contact section in case you need any help.

Add comment