从JSON中获取Null用PHP编码的数据,输出到Java

时间:2013-02-05 02:41:06

标签: java php android json

PHP中的我的JSON输出是这样完成的:

 print json_encode(array('rate' => $topcat, 'hometown' => $hometown, 'talk' => $talk));

我的JSON输出在我的浏览器中显示如下:

{“rate”:“电影”,“故乡”:“西雅图,华盛顿”,“谈话”:“电影”}

在Java / Android中我这样做:

protected void onPostExecute(Void v){

    try {
        JSONArray jArray = new JSONArray(result);
        JSONObject json_data = null;
        for (int i = 0; i < jArray.length(); i++) {
            json_data = jArray.getJSONObject(i);


            Hometown = json_data.getString("hometown");
            FavCategory = json_data.getString("rate");              
            Talk = json_data.getString("talk");



        }
    } catch (JSONException e1) {

    } catch (ParseException e1) {
        e1.printStackTrace();
    }

    if (Hometown.equals("")) {
        Hometown = "Not Specified";
    }

    tvHometown.setText(Hometown);
    tvRate.setText(FavCategory);
    tvTalk.setText(Talk);

    Log.d("Log: ", Hometown + " " + FavCategory + " " + Talk);

}

}

在该日志上,我得到了这个:Seattle, WA, null, null

谁能明白为什么?

编辑:新的Java代码,仍然出现错误:

String homeTown = "", favCategory = "", favTalk = "";
        try {
            JSONObject jsonData = new JSONObject(result);

            homeTown = jsonData.getString("hometown");
            favCategory = jsonData.getString("rate");
            favTalk = jsonData.getString("talk");


            tvHometown.setText(homeTown);
            tvRate.setText(favCategory);
            tvTalk.setText(favTalk);




} catch (JSONException e1) {

    } catch (ParseException e1) {
        e1.printStackTrace();
    }

我得到一个例外:

02-05 08:51:48.078: E/log_tag(22958): Error in http connection org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray

2 个答案:

答案 0 :(得分:4)

尽管the PHP vocabulary,这个JSON的顶级元素:

{"rate":"Movies","hometown":"Seattle, WA","talk":"Movies"}

an object (a key-value mapping), not an array{}是一个死的赠品。

更改此

JSONArray jArray = new JSONArray(result);

到此:

JSONObject jsonData = new JSONObject(result);

从那里开始:

String hometown = jsonData.getString("hometown");
String favCategory = jsonData.getString("rate");              
String talk = jsonData.getString("talk");

请注意as a matter of good Java style,我使用lowerCamelCased变量名。

答案 1 :(得分:0)

你应该有一个方括号来表明它是一个JSONArray你的结果是在JSONObject中如果你想获得每个JSONArray的数据你的结果应该更像这样

{"rate": ["samplevalue","samplevalue"],"Movies" : ["samplevalue","samplevalue"],"hometown":["Seattle, WA"],"talk":["Movies"]}