简体   繁体   中英

error parsing Json with android

I have an error while trying to parse json. Can you help me please? I read the json url, but it gives me an exception when I'm trying to parse the json. The code:

    public String lecturaJsonTusPerlas() {


    DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("http://www.tvnotas.com.mx/rss/feed/tvn-horoscopo.json");
    // Depends on your web service
    httppost.setHeader("Content-type", "application/json");

    InputStream inputStream = null;
    String result = null;
    try {
        HttpResponse response = httpclient.execute(httppost);           
        HttpEntity entity = response.getEntity();

        inputStream = entity.getContent();
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        result = sb.toString();
        return result;

    } catch (Exception e) { 
        Log.d("DEFEKAS","EXCEPCION");

    }
    finally {
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
    }
    return result;

To read json:

        JSONArray jsonArray2 = new JSONArray(lecturaJsonTusPerlas);

        for (int i = 0; i < jsonArray2.length(); i++) {
            JSONObject jsonObject = jsonArray2.getJSONObject(i);

        String atr1 = null;
        boolean var1 = jsonObject.getBoolean(atr1);
        String atr2 = null;
        int var2 = jsonObject.getInt(atr2);
        String atr4 = null;
        String var3 = jsonObject.getString(atr4);
        }

I thing that the url is json because when I'm trying to extract with a google chrome extension I dont have any problem.

What you get is a JSONObject

    JSONObject jb = new JSONObject(lecturaJsonTusPerlas());

Your json looks like below from the link you have used

{ // jsonobject node
    "@attributes": {
        "version": "2.0"
    },
    "channel": {
        "title": "TV Notas",
        "link": "http://www.tvnotas.com.mx",
        "description": "TV Notas - Horoscopos",
        "pubDate": "Mon, 23 Sep 2013 2:30:12 -0500",
        "generator": "http://www.tvnotas.com.mx",
        "language": "es",
        "item": [ // json array of item's
            {
                "title": "Acuario",
                "link": "http://usa.tvnotas.com.mx/horoscopo/1-acuario/",
                "pubDate": "Mon, 23 Sep 2013 02:30:12 -0500",
                "category": "Horoscopo",
                "guid": "http://www.tvnotas.com.mx/horoscopo/1-acuario/",
                "description": "Si has sido soberbio con tus compañeros de trabajo o empleados, con familiares o amigos y no les has perdonado sus malos momentos, ahora se te presentará la oportunidad de estrechar lazos.",
                "enclosure": {
                    "@attributes": {
                        "url": "http://www.tvnotas.com.mx/advf/imagenes/2013/01/50fdbd604f653_150x118.jpg",
                        "length": "3587",
                        "type": "image/jpeg"
                    }
                },
                "elemento": "Aire",
                "planeta": "Urano",
                "signo_compatible": "Cáncer",
                "signo_enemigo": "El excéntrico",
                "numero": "25",
                "arquetipo": "El Loco Sabio",
                "arcangel": "Sakmakrel",
                "color": "Verde",
                "dia_suerte": "28"
            },
            ....

To parse

try {
        JSONObject jb = new JSONObject(lecturaJsonTusPerlas());
        JSONObject job = jb.getJSONObject("channel");
        String channeltitle= job.getString("title");
        String channellink= job.getString("link");
        String channeldecription= job.getString("description");
        String channeldpubdate= job.getString("pubDate");
        String channeldgenerator = job.getString("generator");
        String channeldlanguage = job.getString("language");
        JSONArray jr = job.getJSONArray("item");

        for(int i=0;i<jr.length();i++)
        {
            JSONObject jb1 = (JSONObject) jr.get(i);
            String title = jb1.getString("title");
                            // similar for title link and others 
            JSONObject enclosure = jb1.getJSONObject("enclosure");
            JSONObject attributes= enclosure.getJSONObject("@attributes");
            String url = attributes.getString("url");
            Log.i("....",""+title);
            String elemento= jb1.getString("elemento");
            // similar for others planeta..
        }

        } catch (Exception e) {
        e.printStackTrace();
        }

You might be getting NullPointerException because these lines:

String atr1 = null;
boolean var1 = jsonObject.getBoolean(atr1);
String atr2 = null;
int var2 = jsonObject.getInt(atr2);
String atr4 = null;
String var3 = jsonObject.getString(atr4);

you're trying to parse with "null" reference. See atr1, atr2 and atr4; these strings are initialized with "null".

Try this

JSONObject jObject = new JSONObject(lecturaJsonTusPerlas);

JSONArray jsonArray2 = jObject.getJSONArray("your array key");

        for (int i = 0; i < jsonArray2.length(); i++) {
            JSONObject jsonObject = jsonArray2.getJSONObject(i);

boolean var1 = jsonObject.getBoolean(atr1);
int var2 = jsonObject.getInt(atr2);
String var3 = jsonObject.getString(atr4);

}

don't initialize string values as null.

The reason you are getting this error is your top node of json element is object not an JSON Array.

So to begin parsing you need to write something like this

JSONObject jObject = new JSONObject(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM