开发者

How to call a json webservice through android

I need to access a .Net web service in Rest format using JSON. I m pretty new to this concept and very much confused about how this wo开发者_运维技巧rks.... Any one who can give an overview of this. I need the steps that I need to follow to use JSON. Right now my doubt is how to use JSON to grab to output.


This is the simplest way to parse Json web servie

    String str="url";
    try{
        URL url=new URL(str);
        URLConnection urlc=url.openConnection();
        BufferedReader bfr=new BufferedReader(new InputStreamReader(urlc.getInputStream()));
        String line;
        while((line=bfr.readLine())!=null)
        {
        JSONArray jsa=new JSONArray(line);
        for(int i=0;i<jsa.length();i++)
           {
           JSONObject jo=(JSONObject)jsa.get(i);
                        title=jo.getString("deal_title");  //tag name "deal_title",will return value that we save in title string
                    des=jo.getString("deal_description");
       }
    }
    catch(Exeption e){
    }

Mention Internet permission in android manifest


Gson library can parse your json string automatically to object. Simple example:

 Gson gson = new Gson();
 int[] ints = {1, 2, 3, 4, 5};
 String[] strings = {"abc", "def", "ghi"};

 //(Serialization)
 gson.toJson(ints);     ==> prints [1,2,3,4,5]
 gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]

 //(Deserialization)
 int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 
 ==> ints2 will be same as ints


Here is the code for the Android activity to read from the Web Service and parse the JSON object:

public void clickbutton(View v) {
    try {
        // http://androidarabia.net/quran4android/phpserver/connecttoserver.php

        // Log.i(getClass().getSimpleName(), "send  task - start");
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        //
        HttpParams p = new BasicHttpParams();
        // p.setParameter("name", pvo.getName());
        p.setParameter("user", "1");

        // Instantiate an HttpClient
        HttpClient httpclient = new DefaultHttpClient(p);
        String url = "http://10.0.2.2:8080/sample1/" + 
                     "webservice1.php?user=1&format=json";
        HttpPost httppost = new HttpPost(url);

        // Instantiate a GET HTTP method
        try {
            Log.i(getClass().getSimpleName(), "send  task - start");
            //
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    2);
            nameValuePairs.add(new BasicNameValuePair("user", "1"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost,
                    responseHandler);
            // Parse
            JSONObject json = new JSONObject(responseBody);
            JSONArray jArray = json.getJSONArray("posts");
            ArrayList<HashMap<String, String>> mylist = 
                   new ArrayList<HashMap<String, String>>();

            for (int i = 0; i < jArray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = jArray.getJSONObject(i);
                String s = e.getString("post");
                JSONObject jObject = new JSONObject(s);

                map.put("idusers", jObject.getString("idusers"));
                map.put("UserName", jObject.getString("UserName"));
                map.put("FullName", jObject.getString("FullName"));

                mylist.add(map);
            }
            Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Log.i(getClass().getSimpleName(), "send  task - end");

    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
    }
}

For more details see http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php


you use the json data as follows:

var a=new JSONObject(jsonData);

http://developer.android.com/resources/tutorials/views/hello-mapview.html

Use the data from a to constuct the necessary objects and do the necessary with the same

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜