مشخصات مقاله
آموزش تجزیه کننده ی JSON اندروید

آموزش تجزیه کننده ی JSON اندروید
JSON مخفف JavaScript Object Notation می باشد، که حالتی از مباله ی مستقل داده و بهترین انتخاب برای XML می باشد. این فصل توضیح می دهد که چگونه یک فایل JSON را تجزیه کرده و اطلاغات لازم را از آن استخراج کنیم.
اندروید چهار گروه مختلف برای اجرای داده ی JSON ارائه می دهد که عبارتند از: JSONArray و JSONObject و JSONStringer و JSONTokenizer .
اولین مرحله مشخص کردن فیلدهایی در داده ی JSON می باشد که برای مثال شما به آنها علاقمند هستید. در JSON ارائه شده ما فقط علاقمند به گرفتن دما هستیم.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | { "sys" : { "country" : "GB" , "sunrise" : 1381107633 , "sunset" : 1381149604 }, "weather" :[ { "id" : 711 , "main" : "Smoke" , "description" : "smoke" , "icon" : "50n" } ], "main" : { "temp" : 304.15 , "pressure" : 1009 , } } <button></button> |
یک فایل JSON دارای مولفه های بسیاری می باشد. در اینجا جدول مولفه های JSON و تعریف آنها را مشاهده می کنید.
JSON – تجزیه
برای تجزیه ی آبجکت JSON یک آبجکت از گروه JSONObject ایجاد خواهیم کرد و یک رشته شامل داده ی JSON برای آن مشخص می کنیم. ترکیب آن مانند زیر می باشد.
1 2 3 | String in; JSONObject reader = new JSONObject(in); <button></button> |
آخرین مرحله تجزیه ی است. یک فایل JSON شامل آبجکت های مختلف با جفت های مختلف key/value و غیره می شود. بنابراین JSONObject دارای عملکرد مجزا برای تجزیه ی هرمولفه از فایل JSON می باشد. ترکیب آن به شکل زیر است.
1 2 3 | String in; JSONObject reader = new JSONObject(in); <button></button> |
روش getJSONObject آبجکت JSON را گزارش می دهد. روش getString مقدار رشته ی یک کلید مشخص را گزارش می دهد.
علاوه بر این روش ها، روش های دیگری برای تجزیه ی بهتر JSON توسط این گروه ارائه می شوند که می توانید در لیست زیر مشاهده کنید.
مثال:
در اینجا مثالی را می بینید که گروه JSONObject را توضیح می دهد. این مثال یک برنامه ی پایه ی آب. ه.ا ایجاد می کند که به شما اجازه می دهد JSON را از طریق google weather api تجزیه کنید و نتایج را نشان می دهد.
برای اجرای این مثال نیاز به یک دستگاه واقعی یا یک مقلد دارید.
در زیر محتوای تغییر یافته ی فایل فعالیت اصلی را مشاهده می کنید.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | src/com.example.jsonparser/MainActivity.java. package com.example.jsonparser; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.EditText; public class MainActivity extends Activity { private EditText location,country,temperature,humidity,pressure; private HandleJSON obj; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); location = (EditText)findViewById(R.id.editText1); country = (EditText)findViewById(R.id.editText2); temperature = (EditText)findViewById(R.id.editText3); humidity = (EditText)findViewById(R.id.editText4); pressure = (EditText)findViewById(R.id.editText5); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items //to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true ; } public void open(View view){ String url = location.getText().toString(); String finalUrl = url1 + url; country.setText(finalUrl); obj = new HandleJSON(finalUrl); obj.fetchJSON(); while (obj.parsingComplete); country.setText(obj.getCountry()); temperature.setText(obj.getTemperature()); humidity.setText(obj.getHumidity()); pressure.setText(obj.getPressure()); } } <button></button> |
در زیر محتوای src/com.example.jsonparser/HandleXML.java را مشاهده می کنید.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | package com.example.jsonparser; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import android.annotation.SuppressLint; public class HandleJSON { private String country = "county" ; private String temperature = "temperature" ; private String humidity = "humidity" ; private String pressure = "pressure" ; private String urlString = null ; public volatile boolean parsingComplete = true ; public HandleJSON(String url){ this .urlString = url; } public String getCountry(){ return country; } public String getTemperature(){ return temperature; } public String getHumidity(){ return humidity; } public String getPressure(){ return pressure; } @SuppressLint ( "NewApi" ) public void readAndParseJSON(String in) { try { JSONObject reader = new JSONObject(in); JSONObject sys = reader.getJSONObject( "sys" ); country = sys.getString( "country" ); JSONObject main = reader.getJSONObject( "main" ); temperature = main.getString( "temp" ); pressure = main.getString( "pressure" ); humidity = main.getString( "humidity" ); parsingComplete = false ; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void fetchJSON(){ Thread thread = new Thread( new Runnable(){ @Override public void run() { try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout( 10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */ ); conn.setRequestMethod( "GET" ); conn.setDoInput( true ); // Starts the query conn.connect(); InputStream stream = conn.getInputStream(); String data = convertStreamToString(stream); readAndParseJSON(data); stream.close(); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } static String convertStreamToString(java.io.InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter( "\\A" ); return s.hasNext() ? s.next() : "" ; } } <button></button> |
در زیر محتوای تغییریافته ی xml مربوط به res/layout/activity_main.xml را می بینید./p>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" = "" xmlns:tools= "http://schemas.android.com/tools" android:layout_width= "match_parent" android:layout_height= "match_parent" android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" android:paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools:context= ".MainActivity" > <textview = "" android:id= "@+id/textView1" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_alignparentleft= "true" android:layout_alignparenttop= "true" android:layout_margintop= "15dp" android:text= "@string/location" android:textappearance= "?android:attr/textAppearanceMedium" ></textview> <edittext = "" android:id= "@+id/editText1" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_alignbottom= "@+id/textView1" android:layout_alignparentright= "true" android:ems= "10" ></edittext> <textview = "" android:id= "@+id/textView2" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_alignleft= "@+id/textView1" android:layout_below= "@+id/textView1" android:layout_margintop= "68dp" android:text= "@string/country" android:textappearance= "?android:attr/textAppearanceSmall" ></textview> <textview = "" android:id= "@+id/textView3" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_below= "@+id/textView2" android:layout_margintop= "19dp" android:text= "@string/temperature" android:textappearance= "?android:attr/textAppearanceSmall" ></textview> <textview = "" android:id= "@+id/textView4" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_alignleft= "@+id/textView3" android:layout_below= "@+id/textView3" android:layout_margintop= "32dp" android:text= "@string/humidity" android:textappearance= "?android:attr/textAppearanceSmall" ></textview> <textview = "" android:id= "@+id/textView5" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_alignleft= "@+id/textView4" android:layout_below= "@+id/textView4" android:layout_margintop= "21dp" android:text= "@string/pressure" android:textappearance= "?android:attr/textAppearanceSmall" ></textview> <edittext = "" android:id= "@+id/editText2" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_above= "@+id/textView3" android:layout_torightof= "@+id/textView3" android:ems= "10" > <requestfocus></requestfocus> <edittext = "" android:id= "@+id/editText3" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_alignbaseline= "@+id/textView3" android:layout_alignbottom= "@+id/textView3" android:layout_alignleft= "@+id/editText2" android:ems= "10" ></edittext> <edittext = "" android:id= "@+id/editText4" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_above= "@+id/textView5" android:layout_alignleft= "@+id/editText1" android:ems= "10" ></edittext> <edittext = "" android:id= "@+id/editText5" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_alignbaseline= "@+id/textView5" android:layout_alignbottom= "@+id/textView5" android:layout_alignright= "@+id/editText4" android:ems= "10" ></edittext> <button = "" android:id= "@+id/button1" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_alignleft= "@+id/editText2" android:layout_below= "@+id/editText1" android:onclick= "open" android:text= "@string/weather" ></button> </edittext></relativelayout> <button></button> |
در ادامه محتوای res/values/string.xml می باشد./p>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!--?xml version= "1.0" encoding= "utf-8" ?--> <resources> <string name= "app_name" >JSONParser</string> <string name= "action_settings" >Settings</string> <string name= "hello_world" >Hello world!</string> <string name= "location" >Location</string> <string name= "country" >Country:</string> <string name= "temperature" >Temperature:</string> <string name= "humidity" >Humidity:</string> <string name= "pressure" >Pressure:</string> <string name= "weather" >Weather</string> </resources> <button></button> |
در ادامه محتوای فایل AndroidManifest.xml را مشاهده می کنید.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <!--?xml version= "1.0" encoding= "utf-8" ?--> <manifest xmlns:android= "http://schemas.android.com/apk/res/android" = "" package = "com.example.jsonparser" android:versioncode= "1" android:versionname= "1.0" > <uses-sdk = "" android:minsdkversion= "8" android:targetsdkversion= "17" ></uses-sdk> <uses-permission android:name= "android.permission.INTERNET" ></uses-permission> <application = "" android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/AppTheme" > <activity = "" android:name= "com.example.jsonparser.MainActivity" android:label= "@string/app_name" > <intent-filter> <action android:name= "android.intent.action.MAIN" ></action> <category android:name= "android.intent.category.LAUNCHER" ></category> </intent-filter> </activity></application></manifest> <button></button> |
اجازه بدهید برنامه ی JSONParserخود را اجرا کنیم. فرض می کنیم که در هنگام انجام تنظیمات محیط، AVD خود را ایجاد کرده اید. برای اجرای برنامه از eclipse، یکی از فایل های فعالیت پروژه را باز کنید و روی آیکن Run از تولبار کلیک کنید. Eclipse برنامه را روی AVD شما نصب و آغازمی کند و اگر همه چیز در مورد برنامه و تنظیمات درست باشد، پنجره ی Emulator زیر نمایش داده خواهد شد.

اکنون کاری که باید انجام دهید وارد کردن یک موقعیت در فیلد location می باشد. به عنوان مثال من NewYork را وارد کرده ام. پس از وارد کردن موقعیت، دکمه button را فشار دهید. صفحه ی زیر روی AVD شما نمایش داده خواهد شد.

اکنون وقتی دکمه weather را فشار دهید، برنامه با Google Weather API تماس برقرار می کند و درخواست فایل موقعیت JSON را برای شما کرده و آن را تجزیه می کند. در مورد نیویورک فایل زیر گزارش داده می شود.
1 2 | London Temperature from google weather api <button></button> |
توجه داشته باشید که دمای هوا به کلوین می باشد و اگر بخواهید آن را به فرمت فابل درکی تبدیل کنید، باید آن را به سلسیوس تغییر دهید.