eento
eento

Reputation: 761

Parsing a JSON file from webservice with Android

i'm posting here in order to get some issues about my own project problem.

I want to connect to my webservice from my Android application and get this info into good sources. I'm working with JSON files (wich are good) but only containing JSON Objects.

I used this pretty good source (working very well on his example): http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

You can look at my JSON File :

[
    {
        "id": "2",
        "title": "Printemps du cinema",
        "content": "Decouvrez plein de nouveaux films durant la semaine du printemps du cinema.",
        "date": "2012-07-04",
        "author": "Nicolas  Jeannin",
        "zone": "Mandelieu",
        "area": "Cannes"
    },
    {
        "id": "4",
        "title": "Festival de Cannes",
        "content": "Venez assister a la montee des marches du prestigieux festival !",
        "date": "2012-05-26",
        "author": "Nicolas Teboul",
        "zone": "Cannes",
        "area": "Cannes"
    }
]

I tried to make it running with his method but with a JSON Array composed of 1 element. I always have similar errors :

"Error parsing data org.json.Excption:Value[{"content":".........}] ..cannot be converted to JSONObject."

You can look at my Activity below:

public class AndroidJSONParsingActivity extends ListActivity 
{

    // url to make request
    private static String url = "http://developer.prixo.fr/API/GetEvents?zone=8";
    //private static String url = "http://twitter.com/statuses/public_timeline.json";
    //private static String url = "http://api.androidhive.info/contacts/";
    
    //JSON names
    private static final String TAG_content = "content";
    private static final String TAG_zone = "zone";
    private static final String TAG_id = "id";
    private static final String TAG_area = "area";
    private static final String TAG_title = "title";
    private static final String TAG_date = "date";
    private static final String TAG_author = "author";
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Hashmap for ListView
        ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();
        
        JSONArray event = null; 
        
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();
        
        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        
        try {
                // Getting Array of Contacts
                event = json.getJSONArray("");
                
                JSONObject c = event.getJSONObject(0);
        
                // Storing each json item in variable
                
                String id = c.getString(TAG_id);
                String title = c.getString(TAG_title);
                String content = c.getString(TAG_content);
                String date = c.getString(TAG_date);
                String author = c.getString(TAG_author);
                String zone = c.getString(TAG_zone);
                String area = c.getString(TAG_area);
                
                
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                
                // adding each child node to HashMap key => value
                map.put(TAG_content, content);
                map.put(TAG_title, title);
                map.put(TAG_author, author);

                // adding HashList to ArrayList
                newsList.add(map);
            }
        catch (JSONException e) {
            e.printStackTrace();
        }
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, newsList,R.layout.list_item,new String[] { TAG_content, TAG_title, TAG_author }, new int[] {R.id.name, R.id.email, R.id.mobile });
        setListAdapter(adapter);
        
        // selecting single ListView item
        ListView lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() 
        {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
                String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
                
                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(TAG_content, name);
                in.putExtra(TAG_title, cost);
                in.putExtra(TAG_author, description);
                startActivity(in);

            }
        });
    }

}

And this is the JSONParser :

package com.androidhive.jsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.util.Log;
 
public class JSONParser {
 
    static InputStream is = null;
    static JSONObject jObj = null;
    static String jsonstr = "";
 
    // constructor
    public JSONParser() {
    }
 
    public JSONObject getJSONFromUrl(String url) {
 
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            //HttpGet httpGet = new HttpGet(url);
            
            //HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            jsonstr = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
 
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(jsonstr);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing de Mon fichier: " + e.toString());
        }
 
        // return JSON String
        return jObj;
     }
}

Thanks to help me guys. :)

Upvotes: 0

Views: 2943

Answers (1)

Konstantin Pribluda
Konstantin Pribluda

Reputation: 12367

This is because your JSON defines an JSON array and you try to parse it as JSON object - change it to JSONArray in your parser class and you shall be fine.

Another issue is memorz management - you are reallocating strings and parse with vanilla JSON parser provided with android. This works, but has terrible memory consumption and lot of allocations - pretty slow for bigger data. Use pull parser instead ( like GSON, scaled down version is only 16K )

You may also consider kind of databinding to create java objects out of JSON - you may grab my library ( also available on maven central):

https://github.com/ko5tik/jsonserializer

Then it will be as easy as:

       InputStream inputStream = getResources().openRawResource(preferences.getRecognitionConfig());
        InputStreamReader reader = new InputStreamReader(inputStream);


        JsonReader jreader = new JsonReader(reader);          
        jreader.setLenient(true);
        final RecognitionDataContainer recognitionContainer = JSONUnmarshaller.unmarshall(jreader, RecognitionDataContainer.class);

        reader.close();

(RecognitionDataContainer is top level object resembling JSON structure )

Upvotes: 2

Related Questions