gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:23:14 25 4
gpt4 key购买 nike

我知道可能有人会问这个问题,但我无法得到具体答案。我有一个 json 字符串:

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();

但是,我似乎无法获得入口点,无论我如何尝试,我都无法获得任何东西,感谢您提前提供的帮助。

最佳答案

如果您的 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} 大括号。

希望这有帮助。

关于java - 从 JSON 字符串中提取单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18972493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com