2017-06-03 8 views
1

まず、この愚かな質問を申し訳ありません。サーバー(Java)からJSONを読んでください

このJSONファイルをサーバーから読み取る方法について、誰でもコードを手伝ってもらえますか?私は、いくつかのチュートリアルを見てから自分のJavaコードを台無しにしました。

[ 
    { 
    "name": "Coleen Sanford", 
    "location": { 
     "latitude": -60.489023, 
     "longitude": -32.311668 
    } 
    }, 
    { 
    "name": "Bethany Church", 
    "location": { 
     "latitude": -1.304805, 
     "longitude": -80.670287 
    } 
    }, 
    { 
    "name": "Kristy Ware", 
    "location": { 
     "latitude": -46.443562, 
     "longitude": -46.426997 
    } 
    }, 
    { 
    "name": "Avery Navarro", 
    "location": { 
     "latitude": 35.719469, 
     "longitude": -172.783006 
    } 
    }, 
    { 
    "name": "Robyn Cruz", 
    "location": null 
    }, 
    { 
    "name": "Vinson Hays", 
    "location": null 
    } 
] 

これは私のコードです:

/** 
* Async task class to get json by making HTTP call 
*/ 
private class GetContacts extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // Showing progress dialog 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage("Please wait..."); 
     pDialog.setCancelable(false); 
     pDialog.show(); 

    } 

    @Override 
    protected Void doInBackground(Void... arg0) { 
     HttpHandler sh = new HttpHandler(); 

     // Making a request to url and getting response 
     String jsonStr = sh.makeServiceCall(url); 

     Log.e(TAG, "Response from url: " + jsonStr); 

     if (jsonStr != null) { 
      try { 
       JSONObject jsonObj = new JSONObject(jsonStr); 

       // Getting JSON Array node 
       JSONArray contacts = new JSONArray (jsonStr); 

       // looping through All Contacts 
       for (int i = 0; i < contacts.length(); i++) { 
        JSONObject c = contacts.getJSONObject(i); 

        String name = c.getString("name"); 

        // Phone node is JSON Object 
        JSONObject phone = c.getJSONObject("location"); 
        String latitude = phone.getString("latitude"); 
        String longitude = phone.getString("longitude"); 

        // tmp hash map for single contact 
        HashMap<String, String> contact = new HashMap<>(); 

        // adding each child node to HashMap key => value 
        contact.put("name", name); 
        contact.put("latitude", latitude); 
        contact.put("longitude", longitude); 

        // adding contact to contact list 
        contactList.add(contact); 
       } 
      } catch (final JSONException e) { 
       Log.e(TAG, "Json parsing error: " + e.getMessage()); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           "Json parsing error: " + e.getMessage(), 
           Toast.LENGTH_LONG) 
           .show(); 
        } 
       }); 

      } 
     } else { 
      Log.e(TAG, "Couldn't get json from server."); 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        Toast.makeText(getApplicationContext(), 
          "Couldn't get json from server. Check LogCat for possible errors!", 
          Toast.LENGTH_LONG) 
          .show(); 
       } 
      }); 

     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     // Dismiss the progress dialog 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 
     /** 
     * Updating parsed JSON data into ListView 
     * */ 
     ListAdapter adapter = new SimpleAdapter(
       MainActivity.this, contactList, 
       R.layout.list_item, new String[]{"name", "latitude", 
       "longitude"}, new int[]{R.id.name, 
       R.id.latitude, R.id.longitude}); 

     lv.setAdapter(adapter); 
    } 

}} 
+0

使用 'optString'「いくつかの値のcuzがnullのプラス' jsonStr'は –

答えて

2

まずあなたがシリアライズとJSON

をデシリアライズ用のGoogleパワードツールはその後、あなたにgson依存関係を追加されGsonを使用することができますコード、

compile 'com.google.code.gson:gson:2.7' 

次​​に行うべきことは、jsonデータをシリアライズするためのサンプルモデルクラスをいくつか作成し、このlinkを使用してjsonデータを貼り付けて対応するクラスを作成することです。

次にJavaコードです(ベースモデルクラス名あるUserLocation

Userlocation

public class UserLocation{ 
     private Location location; 

     private String name; 

     public Location getLocation() 
     { 
      return location; 
     } 

     public void setLocation (Location location) 
     { 
      this.location = location; 
     } 

     public String getName() 
     { 
      return name; 
     } 

     public void setName (String name) 
     { 
      this.name = name; 
     } 
    } 

場所

public class Location { 
    private double longitude; 

    private double latitude; 

    public double getLongitude() 
    { 
     return longitude; 
    } 

    public void setLongitude (double longitude) 
    { 
     this.longitude = longitude; 
    } 

    public double getLatitude() 
    { 
     return latitude; 
    } 

    public void setLatitude (double latitude) 
    { 
     this.latitude = latitude; 
    } 
} 
コードで

List<UserLocation> userLocationList = Arrays.asList(new Gson().fromJson(yourResponseString, UserLocation[].class)); 

これだ、すべてが

コーディングハッピーこのuserLocationList下になります。.. :)

+0

jsonarrayで再びPOJOクラスを確認し、JSONレスポンス –

+0

することができますしてください何が間違っているのかを指摘する@quicklearner – Sanoop

+0

あなたの答えを編集して私に短い緯度と経度を教えさせてください。文字列型ではないjsonレスポンスでダブルタイプです –

0

あなたが取得する必要があります。この をお試しくださいコンタクト配列が正しく、またダブルタイプの緯度と経度

if (jsonStr != null) { 
     try { 
      JSONObject jsonObj = new JSONObject(jsonStr); 
      // Getting JSON Array node 
      JSONArray contacts = new JSONArray(); 
      contacts=jsonObj.getJSONArray("keyforarray") 
      // looping through All Contacts 
      for (int i = 0; i < contacts.length(); i++) { 
       JSONObject c = contacts.getJSONObject(i); 
       String name = c.getString("name"); 
       // Phone node is JSON Object 
       JSONObject phone = c.getJSONObject("location"); 
       double latitude = phone.getDouble("latitude"); 
       double longitude = phone.getDouble("longitude"); 
       // tmp hash map for single contact 
       HashMap<String, String> contact = new HashMap<>(); 
       // adding each child node to HashMap key => value 
       contact.put("name", name); 
       contact.put("latitude", String.valueOf(latitude)); 
       contact.put("longitude", String.valueOf(longitude)); 
       // adding contact to contact list 
       contactList.add(contact); 
      } 
     } catch (final JSONException e) { 
      Log.e(TAG, "Json parsing error: " + e.getMessage()); 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        Toast.makeText(getApplicationContext(), 
          "Json parsing error: " + e.getMessage(), 
          Toast.LENGTH_LONG) 
          .show(); 
       } 
      }); 

     } 
    } 
0

ダウンロードのJSONファイルをAsyncTaskで試してみてください。このメソッドは、jsonでStringを返しました。

@Override 
    protected String doInBackground(String... urls) { 
     try { 
      URL url = new URL(urls[0]); 

     urlConnection = (HttpURLConnection) url.openConnection(); 
     urlConnection.setRequestMethod("GET"); 
     urlConnection.setRequestProperty("Authorization", "Basic that_my_Basic_Auth"); 
     urlConnection.connect(); 

     InputStream inputStream = urlConnection.getInputStream(); 
     StringBuffer buffer = new StringBuffer(); 

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

     String line; 
     while ((line = reader.readLine()) != null) { 
      buffer.append(line); 
     } 

     resultJson = buffer.toString(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return resultJson; 
} 

次に、あなたはこのようにJSONObjectを取得することができます:

JSONObject json = new JSONObject(new MyAsyncTask().execute(string_url).get()); 
関連する問題