วิธีแยกวิเคราะห์ JSON หลายอาร์เรย์ (Java)

ขณะนี้ฉันกำลังทำงานในโครงการที่ต้องใช้ละติจูดและลองจิจูดของที่อยู่ที่ระบุ (อินพุต) Google Maps API กลับมาในรูปแบบ json และฉันได้ค้นคว้าข้อมูลแล้วและพบว่า json-simple เป็นตัวเลือกที่ดีที่สุดสำหรับโครงการของฉัน ฉันมีรหัสนี้รวมถึงสตริงเอาต์พุตจาก Google Maps API และขอขอบคุณสำหรับความช่วยเหลือในการแยกวิเคราะห์อย่างถูกต้อง หมายเหตุด้วย: การโทร: MapTile.receiveJson เพิ่งส่งคืนสตริงจาก API ของ Google (ลิงก์ด้านล่าง)

try {
            String jsonAdr = MapTile.receiveJson("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA");
            JSONParser parser = new JSONParser();
            JSONObject json = (JSONObject)parser.parse(jsonAdr);  
            System.out.println("lat=" + json.get("address_components"));
        } catch (Exception e1) {e1.printStackTrace();System.out.println("Error contacting google or invalid input");}

นี่คือเอาต์พุตสตริงที่แน่นอนจาก API ของ Google:

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA

ฉันรู้ว่าฉันสามารถแยกวิเคราะห์สตริงได้ แต่จะไม่มีประสิทธิภาพเนื่องจากฉันจะใช้ API ของ Google มากขึ้น ฉันยังได้ดูสแต็กโอเวอร์โฟลว์อื่นๆ รวมถึงเว็บไซต์ JSON ของพวกเขาด้วย แต่ไม่พบตัวอย่างที่มีอาร์เรย์ JSON หลายรายการ เช่น ที่ส่งคืนโดย Google

ความช่วยเหลือใด ๆ ที่ชื่นชมอย่างมาก


person user3740929    schedule 14.06.2014    source แหล่งที่มา
comment
ก่อนที่คุณจะได้รับ address_components คุณต้องได้รับอาร์เรย์ results จากนั้นจากองค์ประกอบแรก (หรือองค์ประกอบใดๆ ) จากนั้นคุณจึงสามารถอ่าน address_components ได้   -  person Philipp Gayret    schedule 14.06.2014


คำตอบ (2)


นี่คือวิธีแก้ปัญหา:

โดยพื้นฐานแล้วฉันทำแบบสแตนด์อโลนและแยกวิเคราะห์ JSON ของคุณดังนี้:

ครั้งแรก : นี่คือวิธีที่ฉันใช้ในการแยกวิเคราะห์ JSON:

public String loadJSON(String someURL) {

        String json = null;
        HttpClient mHttpClient = new DefaultHttpClient();
        HttpGet mHttpGet = new HttpGet(someURL);

        try {

            HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
            StatusLine statusline = mHttpResponse.getStatusLine();
            int statusCode = statusline.getStatusCode();
            if (statusCode != 200) {

                return null;

            }
            InputStream jsonStream = mHttpResponse.getEntity().getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    jsonStream));

            StringBuilder builder = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {

                builder.append(line);

            }

            json = builder.toString();

        } catch (IOException ex) {

            ex.printStackTrace();

            return null;
        }
        mHttpClient.getConnectionManager().shutdown();
        return json;

    }

ที่สอง : ใช้งาน Async เพื่อดาวน์โหลดข้อมูล:

public class BackTask extends AsyncTask<Void, Void, Void> {

        String url;

        public BackTask(String URL) {
            super();
            this.url = URL;

        }

        @Override
        protected Void doInBackground(Void... params) {

            getData(url);
            return null;
        }

    }

ที่สาม: วิธีการรับข้อมูลและแยกวิเคราะห์ ฉันได้แสดงความคิดเห็นบางส่วนสำหรับส่วนนี้เนื่องจากยาวกว่าปกติเล็กน้อย

public void getData(String URL) {

        try {
            JSONObject mainJsonObject = new JSONObject(loadJSON(URL));
            // Log.d("JSON Data : ", mainJsonObject.toString());

            String Status = mainJsonObject.getString("status");
            Log.d("JSON Status : ", Status + "\n" + "---------------------");

            JSONArray mainArray = mainJsonObject.getJSONArray("results");
            // Log.d("JSON Array : ", mainArray.toString());

            for (int i = 0; i < mainArray.length(); i++) {

                JSONObject insideJsonObject = mainArray.getJSONObject(i);

                if (insideJsonObject != null) {

                    String address_components = insideJsonObject
                            .getString("address_components");
                    // Log.d("Inside JSON Array : ", address_components);

                    JSONArray addressJSON = insideJsonObject
                            .getJSONArray("address_components");
                    // Log.d("Inside JSON ADDress : ", addressJSON.toString());

                    String formatted_address = insideJsonObject
                            .getString("formatted_address");
                    Log.d("Inside JSON formatted_address : ", formatted_address
                            + "\n" + "-----------");

                    for (int ji = 0; ji < mainArray.length(); ji++) {

                        JSONObject geoMetryJO = mainArray.getJSONObject(ji);

                        if (geoMetryJO != null) {

                            JSONObject geometry = geoMetryJO
                                    .getJSONObject("geometry");
                            // Log.d("Inside JSON geometry : ",
                            // geometry.toString()+"\n"+"----------");

                            String location_type = geometry
                                    .getString("location_type");
                            Log.d("Inside JSON location_type : ", location_type
                                    + "\n" + "------------");

                            JSONObject locationJSONObject = geometry
                                    .getJSONObject("location");

                            String Latitude = locationJSONObject
                                    .getString("lat");
                            Log.d("Inside JSON Latitude : ", Latitude + "\n"
                                    + "--------------");
                            String Longitude = locationJSONObject
                                    .getString("lng");
                            Log.d("Inside JSON Longitude : ", Longitude + "\n"
                                    + "------------");

                            JSONObject viewportJSONObject = geometry
                                    .getJSONObject("viewport");
                            // Log.d("Inside JSON viewportJSONObject : ",
                            // viewportJSONObject.toString()+"\n"+"------------");

                            JSONObject northeastJSONObject = viewportJSONObject
                                    .getJSONObject("northeast");
                            String Lat = northeastJSONObject.getString("lat");
                            Log.d("Inside JSON Lat : ", Lat + "\n"
                                    + "------------");
                            String Lon = northeastJSONObject.getString("lng");
                            Log.d("Inside JSON Lon : ", Lon + "\n"
                                    + "------------");

                            JSONObject southwestJSONObject = viewportJSONObject
                                    .getJSONObject("southwest");
                            String south_Lat = southwestJSONObject
                                    .getString("lat");
                            Log.d("Inside JSON south_Lat : ", south_Lat + "\n"
                                    + "------------");
                            String south_Lon = southwestJSONObject
                                    .getString("lng");
                            Log.d("Inside JSON south_Lon : ", south_Lon + "\n"
                                    + "------------");
                        }

                    }

                    for (int k = 0; k < addressJSON.length(); k++) {

                        JSONObject addressJSONObject = addressJSON
                                .getJSONObject(k);

                        if (addressJSONObject != null) {

                            String long_name = addressJSONObject
                                    .getString("long_name");
                            Log.d("Inside JSON LongName : ", long_name);
                            String short_name = addressJSONObject
                                    .getString("short_name");
                            Log.d("Inside JSON ShortName : ", short_name);

                            JSONArray addressJSONArray = addressJSONObject
                                    .getJSONArray("types");
                            Log.d("Inside JSON JSONADD : ",
                                    addressJSONArray.toString() + "\n"
                                            + "-------------");

                        }

                    }

                    JSONArray insideJsonArray = insideJsonObject
                            .getJSONArray("types");
                    Log.d("Inside JSON Types : ", insideJsonArray.toString());
                    String street = insideJsonObject.getString("types");
                    Log.d("Inside JSON Street : ", street);

                }

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

หลังจากได้รับข้อมูลทั้งหมดแล้ว คุณสามารถนำไปใช้ในรูปแบบใดก็ได้ที่ต้องการ เนื่องจากส่วนใหญ่อยู่ในรูปแบบสตริง คุณสามารถคัดลอกและวางวิธีนี้และควรจะทำงานได้ดี

ที่สี่ : ในเมธอด onCreate() เพิ่งดำเนินการงานดังนี้:

public static final String URL = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA";
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new BackTask(URL).execute();

    }

นี่เป็นวิธีแก้ปัญหาที่สมบูรณ์สำหรับคำถามนี้ โปรดแจ้งให้เราทราบหากมีคำถามใดๆ เกี่ยวกับเรื่องนี้ หวังว่านี่จะช่วยได้..ขอให้โชคดี.. :)

person mike20132013    schedule 16.06.2014

ฉันทำสิ่งนี้เพื่อ formatted_address ฉันพิมพ์หล่ออย่างชัดเจนที่นี่ แต่เมธอด getJSONArray () และ getJSONObject() จะทำการพิมพ์ด้วยเช่นกัน

// parse the Result String to JSON
JSONObject myJSONResult = new JSONObject(results);
for (int i = 0; i <((JSONArray) myJSONResult.get("results")).length(); i++) 
    System.out.println(((JSONObject) ((JSONArray) myJSONResult.get("results")).get(i)).get("formatted_address")); // This is your final options.
person D V Santhosh Kiran    schedule 08.04.2015