Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何从url获取JSON数据?_Android_Json - Fatal编程技术网

Android 如何从url获取JSON数据?

Android 如何从url获取JSON数据?,android,json,Android,Json,这是我在textview中获取JSON数据的代码。JSON数据仅在我的代码中。 现在,如果我的数据位于某个URL中,那么如何获取这些数据? 旧的答案使用的是defaultHTTPClient,它不再受支持,我尝试使用改型和截击,但无法理解 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(sav

这是我在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();}
}
公共类MainActivity扩展活动{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView输出=(TextView)findViewById(R.id.textView1);
字符串strJson=“{\'Employee\”:[{\'id\”:\'101\,\'name\:\'Sonoo Jaiswal\,\'salary\:\'50000\,{\'id\:'102\,\'name\:'Vimal Jaiswal\,\'salary\:'60000\“}”;
字符串数据=”;
试一试{
//从JSON字符串创建根JSONObject。
JSONObject jsonRootObject=新的JSONObject(strJson);
//获取包含JSONObject的JSONArray实例
JSONArray JSONArray=jsonRootObject.optJSONArray(“员工”);
//迭代jsonArray并打印JSONObject的信息
for(int i=0;i
像这样:

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
}
请尝试以下代码:

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);
}
编辑

如果找不到httpclient,请使用

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

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

 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;
从上面的字符串数据中删除“\”。然后尝试解析。您的json无效


查看

你可以参考你想要做的事情吗?我只想从这个url获取数据,并在文本视图中显示它们。可能的重复可以从url教程中了解如何解析android应用程序中的JSON数据OP询问如何从url链接的api解析,而不是从本地解析。您好,谢谢,但我正在使用api 23和这个httpclient不在那里。然后使用截击。我编辑了答案。引用它@shwetabxinghand,此外还引用了这个。从响应中解析与我在那篇文章中提到的相同..快乐编码。。
   @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();
 }

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