如何从url获取JSON数据?

时间:2016-02-24 09:51:16

标签: android json

这是我在textview中获取JSON数据的代码.JSON数据仅在我的代码中。 现在,如果我的数据在某个URL中,那么我该如何获取这些数据呢? 旧的答案使用defaultHTTPClient,这是不再支持的,我尝试使用改造和排球,但无法理解。

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView output = (TextView) findViewById(R.id.textView1);

    String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswal\",\"salary\":\"50000\"},{\"id\":\"102\",\"name\":\"Vimal Jaiswal\",\"salary\":\"60000\"}] }";

    String data = "";
    try {
        // Create the root JSONObject from the JSON string.
        JSONObject  jsonRootObject = new JSONObject(strJson);

        //Get the instance of JSONArray that contains JSONObjects
        JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");

        //Iterate the jsonArray and print the info of JSONObjects
        for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            int id = Integer.parseInt(jsonObject.optString("id").toString());
            String name = jsonObject.optString("name").toString();
            float salary = Float.parseFloat(jsonObject.optString("salary").toString());

            data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
        }
        output.setText(data);
    } catch (JSONException e) {e.printStackTrace();}
}

4 个答案:

答案 0 :(得分:1)

<强> 修改

如果找不到httpclient,请使用Volley

此外,解析脚本与下面提到的相同。

我已经写了Blog。请参考。希望能帮助到你。让我克隆我的博客以符合您的要求。请使用正确的命名。这是解析输出。

 public class GridUI extends Activity {
 ArrayList<Persons> personsList;
 GridView gridView;
 GridAdapter gridAdapter;
private static final String   url="http://www.zippytrailers.com/funlearn/topicsMap";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gridview);
    personsList= new ArrayList<Persons>();
 new JSONAsyncTask().execute(url);
 gridView=(GridView)findViewById(R.id.gridview);
 gridAdapter = new GridAdapter(this, R.layout.gridview_row, personsList);
 gridView.setAdapter(gridAdapter);

 }
 class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
 ProgressDialog dialog;
 @Override
  protected void onPreExecute() {
  // TODO Auto-generated method stub
  super.onPreExecute();
  dialog=new ProgressDialog(GridUI.this);
  dialog.setMessage("Loading, please wait");
  dialog.setTitle("Connecting server");
  dialog.show();
  dialog.setCancelable(false);

  }


   @Override
  protected Boolean doInBackground(String... urls) {
      try {

//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);

// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();

 if(status==200){
 HttpEntity entity = response.getEntity();
 String data = EntityUtils.toString(entity);
  JSONObject jsono=new JSONObject(data);
  JSONArray jarray = jsono.getJSONArray("results");
  for (int i = 0; i < jarray.length(); i++) {
   JSONObject object = jarray.getJSONObject(i);

   Persons name = new Persons();

   name.setName(object.getString("syllabus"));
   name.setDescription(object.getString("grade"));
   name.setDob(object.getString("subject"));
   name.setCountry(object.getString("topic"));
   name.setHeight(object.getString("id"));

   personsList.add(name);
  }
  return true;
 }

} catch (ParseException e1) {
 e1.printStackTrace();
} catch (IOException e) {
 e.printStackTrace();
} catch (JSONException e) {
 e.printStackTrace();
}
return false;

}

   @Override
  protected void onPostExecute(Boolean result) {
  super.onPostExecute(result);
  dialog.cancel();
  gridAdapter.notifyDataSetChanged();
  if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from   server", Toast.LENGTH_LONG).show();
 }

}

答案 1 :(得分:1)

{  
   "Employee":[  
      {  
         "id":"101",
         "name":"Sonoo Jaiswal",
         "salary":"50000"
      },
      {  
         "id":"102",
         "name":"Vimal Jaiswal",
         "salary":"60000"
      }
   ]
}

删除&#34; \&#34;从你上面的字符串数据。然后尝试解析。你的json是无效的。

https://jsonformatter.curiousconcept.com/

上查看

答案 2 :(得分:0)

像这样:

String myURL = "https://www.myurl.com/file.json";
String jsonResponse = null;
try {
    jsonResponse = (String) new RetrieveJSONTask(myURL).execute().get();
} catch (ExecutionException | InterruptedException e) {
    // Do something
}

如果你需要获得一个物体,你可以这样做:

JSONObject jsonObject = null;
try {
    jsonObject = new JSONObject(jsonResponse);

    // Here you get an specific tag named "title" from the first object of an array named "itens"
    String title = jsonObject.getJSONArray("items").getJSONObject(0).getString("title");

} catch(JSONException e) {
     // Do something
}

答案 3 :(得分:0)

试试这段代码:

try {
    URL url = new URL("http://www.zippytrailers.com/funlearn/topicsMap");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line + "\n");
    }
    String result = sb.toString();
    System.out.println("result"+result);
} catch (Exception e){
    System.out.println(" error"+e);
}