从JSON字符串中提取单个元素

时间:2013-09-24 03:27:46

标签: java json facebook

我知道这可能会被问到,但我无法得到具体答案。我有一个json String:

GraphObject{graphObjectClass=GraphPlace, state={"id":"268367713308665","category":"School","location":{"state":"","zip":"","longitude":32.631482614136,"latitude":0.24519375867929,"country":"Uganda","city":"Kampala","street":"PO BOX 28493"},"category_list":[{"id":"365182493518892","name":"School"}],"name":"Little Wonders Montessori"}}
GraphObject{graphObjectClass=GraphPlace, state={"id":"142442605900768","category":"Education","location":{"state":"","zip":"","longitude":32.606752647018,"latitude":0.28746491511647,"country":"Uganda","city":"Kampala","street":"Heritage\/ Kiwafu Stage, Wheeling Zone, Gaba Road, Kansanga"},"category_list":[{"id":"151676848220295","name":"Education"}],"name":"Wisdomgate Pre-School, Kansanga."}}

当我查询附近的地方时,我从Facebook获取,我想提取纬度,经度,类别和名称。 这就是我想要的

public void onCompleted(List<GraphPlace> places, Response response) {
    //Toast.makeText(getActivity(), (CharSequence) places.listIterator(), Toast.LENGTH_LONG).show();
    ListIterator<GraphPlace> x =    places.listIterator();
    while(x.hasNext()){
        String f = x.next().toString();
        Toast.makeText(getActivity(), f, Toast.LENGTH_LONG).show();
        mytext.setText(f);
        try {
            JSONObject json = new JSONObject(f);
            JSONArray array = json.getJSONArray( "GraphPlace" );
            Toast.makeText(getActivity(), array.length(), Toast.LENGTH_LONG).show();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}   
});
request.executeAsync(); 

但是,我似乎无法获得切入点,无论我尝试多少,我都无法得到任何结果。感谢您提前获得帮助。

1 个答案:

答案 0 :(得分:1)

如果您的JSON字符串如下所示:

{"id":"268367713308665","category":"School","location":{"state":"","zip":"","longitude":32.631482614136,"latitude":0.24519375867929,"country":"Uganda","city":"Kampala","street":"PO BOX 28493"},"category_list":[{"id":"365182493518892","name":"School"}],"name":"Little Wonders Montessori"}}

获取纬度和经度将是:

        JSONObject json = new JSONObject(yourJSONVariableHere);
        JSONObject location = json.getJSONObject( "Location" );
        String lat = location.getString("latitude");
        String long = location.getString("longitude");

对于latlong变量,您可以根据JSON的值分配intlong。如果您更改变量类型,则会为相应的变量值执行getInt()getLong

要记住的其他事项是你有一个嵌套对象,它包含latlong,所以你必须得到它,然后解析它。如果您有嵌套数组或其他对象,也是如此。目前您正在使用getJSONArray,但JSON中的数组有[array, array]或方括号,其中JSON对象具有{object, object}花括号。

希望这会有所帮助。