This post demonstrate client\server interaction using JSON.
The client is android app and the server is asp.net based.
1. Android Client
Java supports JSON in terms of the classes :
- JSONArray
- JSONObject
2. ASP.Net Server
.Net supports JSON in terms of DataContractJsonSerializer
3. Source Sample
JSONClient.zip
JSONWebSite.zip
This sample includes :
1. The client send GET request to an ASP.Net server
2. The server responds with JSON array :
[ {UserId="John" ,Latitude = 33.33 , Longitude = 44.56 ,Location = "some place 1" },
{UserId="Jim" ,Latitude = 44.33 , Longitude = 55.56 ,Location = "some place 2" }]
which is written via DataContractJsonSerializer and Response.Write to the client
3. The client parse the JSON array via classes JSONArray and JSONObject and write it to a TextView
Client
uses HttpURLConnection as done in android-connection-to-internet-1
The new stuf here is the parsing of the JSON array
protected void onPostExecute(Object result) {
try {
String strOut="";
JSONArray json = new JSONArray((String)result);
for (int i = 0; i < json.length(); ++i) {
JSONObject rec = json.getJSONObject(i);
strOut += String.format("UserId : %s ,Latitude : %f ,Longitude : %f ,Location : %s\n",
rec.getString("UserId"),rec.getDouble("Latitude"),
rec.getDouble("Longitude"),rec.getString("Location"));
}
textViewMessage.setText(strOut);
}
catch (JSONException e) {
textViewMessage.setText(e.getMessage());
}
}
MainActivity.javaThis is basically like android-connection-to-internet-1 beside the JSON stuff
package com.example.jsonclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
urlText = (EditText) findViewById(R.id.editTextURL);
textViewURL = (TextView) findViewById(R.id.textViewURL);
textViewMessage = (TextView) findViewById(R.id.textViewMessage);
}
// When user clicks button, calls AsyncTask.
// Before attempting to fetch the URL, makes sure that there is a network connection.
public void myClickHandler(View view) {
// Gets the URL from the UI's text field.
String stringUrl = urlText.getText().toString();
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageText().execute(stringUrl);
} else {
textViewMessage.setText("No network connection available.");
}
}
// Uses AsyncTask to create a task away from the main UI thread. This task takes a
// URL string and uses it to create an HttpUrlConnection. Once the connection
// has been established, the AsyncTask downloads the contents of the web page as
// an InputStream. Finally, the InputStream is converted into a string, which is
// displayed in the UI by the AsyncTask's onPostExecute method.
private class DownloadWebpageText extends AsyncTask {
@Override
protected String doInBackground(Object... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl((String) urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(Object result) {
try {
String strOut="";
JSONArray json = new JSONArray((String)result);
for (int i = 0; i < json.length(); ++i) {
JSONObject rec = json.getJSONObject(i);
strOut += String.format("UserId : %s ,Latitude : %f ,Longitude : %f ,Location : %s\n",
rec.getString("UserId"),rec.getDouble("Latitude"),
rec.getDouble("Longitude"),rec.getString("Location"));
}
textViewMessage.setText(strOut);
}
catch (JSONException e) {
textViewMessage.setText(e.getMessage());
}
}
}
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String line;
String page = "";
line = in.readLine();
String contentAsString="";
while (line != null)
{
contentAsString = contentAsString + line;
line = in.readLine();
}
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
//Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
private static final String DEBUG_TAG = "HttpExample";
private EditText urlText;
private TextView textViewURL;
private TextView textViewMessage;
}
Server
The server is ASP.Net based.
It create JSON array via DataContractJsonSerializer and send to the client using Response.Write .
The server uses helper class name JsonHelper
main.aspx
CJsonHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization.Json; using System.Web; using System.IO; using System.Text; ///CTableRow.cs/// Summary description for Class1 /// public class JsonHelper { ////// JSON Serialization /// public static string JsonSerializer<T>(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; } ////// JSON Deserialization /// public static T JsonDeserialize<T>(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; ///Run the application to create :/// Summary description for Class1 /// public class CTableRow { public string UserId; public double Latitude; public double Longitude; public string Location; }
Click the Get button to crete
These are the exact info inserted by the server
Nathan




No comments:
Post a Comment