从JSON获取数据?

时间:2018-10-29 09:19:03

标签: android json strava

我想从中获取用户名 Json url。 我有这段代码,但是它不允许我得到表示

的数据
  

Json解析错误

代码如下:

HttpHandler.java

public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;

// URL to get contacts JSON
private static String url = "https://someLink";

ArrayList<HashMap<String, String>> contactList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    contactList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);

    new GetContacts().execute();
}

/**
 * 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 = jsonObj.getJSONArray("");

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

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

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

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

                    // 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[]{"username"}, new int[]{R.id.name});

        lv.setAdapter(adapter);
    }

}
}

这是我在Google上发现的一个示例,试图根据需要对其进行一些更改。我放置了一个空的JsonArray。我也尝试了其他示例,但我不明白出了什么问题。

**

>新问题

如果我的网址是这样?与其他网址有什么区别?

new Json

**

4 个答案:

答案 0 :(得分:2)

请在 MainActivity 中编辑您的代码,以从json字符串中获取用户名,如下所示:

if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr); 
if(jsonObj !=null) 
{
String name = jsonObj .getString("username");
}
}

答案 1 :(得分:2)

在输出中没有要解析的数组。您的URL给您一个对象。您的代码应该是这样的

class video_rental_copy(osv.osv):
    """..."""
    _name = 'video_rental.copy'
    _columns = {
        'name': fields.char('Reference', size=32, required=True, help='xxx'),
        'product_id': fields.many2one('product.product','Film',required=True, help='...'),
        'period_id': fields.many2one('video_rental.period','Period',required=True, help='...'),
        'state': fields.selection([('rented','Rented'),('free','Free')],'State of the film',readonly=True),
        'actived': fields.boolean('Active'),
        'rental_id': fields.one2many('video_rental.rentals', 'copy_id', 'Videos',required=False,readonly=True),

    }
    _sql_constraints = [
     ('reference', 'unique(name)', 'It already exists another reference with the same reference!'),

     ]
    _defaults = {
        'state' : 'free',
        'actived' : 'True',
    }



video_rental_copy()

class video_rental_rentals(osv.osv):
    """..."""
    _name = 'video_rental.rentals'
    _columns = {
        'copy_id': fields.many2one('video_rental.copy','Copy',required=True, help='...'),
        'state': fields.related('copy_id','state',type='char',string='State',store=False),
        'period_id': fields.related('copy_id','period_id',type='many2one',relation='video_rental.period',string='Period',store=False,readonly=True),
        'days': fields.related('period_id','days',type='integer',relation='video_rental.period',string='Days',store=False,readonly=True),
        'partner_id': fields.many2one('res.partner', 'Customer',required=True, help='...'),
        'rental_date': fields.datetime('Rental Date',required=True, help='...'),
        'limit_date': fields.function(_compute_limit_date,type='datetime',string='Limit Date',store=True),
        'return_date': fields.datetime('Return Date',help='...'),


    }

    _constraints = [
    (_check_my_return_date, 'Return date before rental date!', ['return_date']),
    (_check_copy_id_state, 'State must be free!', ['state'])
       ]
    def create(self,cr,uid,vals,context=None):

        video_rental_copy_obj = self.pool.get('video_rental.copy')
        ids = video_rental_copy_obj.search(cr,uid,[('name','=','copy_id')])
        values={'state':'rented'}

        video_rental_copy_obj.write(self, cr, uid, ids, values, context=None)
        res=super(video_rental_rentals,self).create(cr,uid,vals)


        return res
video_rental_rentals()

答案 2 :(得分:1)

我建议您使用这个。

public class HttpGetResources extends AsyncTask<String, Void, Object> {

    @SuppressLint("StaticFieldLeak")
    private ProgressBar progressBar;
    private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
    private String urlString;
    private String apiName;
    private Class Response_Class;
    private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
    private Context context;

    public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
        this.Response_Class = Response_Class;
        this.apiName = apiName;
        this.urlString = urlString;
        this.context=context;

    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();


    }

    @Override
    protected void onPostExecute(Object response) {
        super.onPostExecute(response);

    }
    HttpURLConnection conn = null;
    OutputStreamWriter out = null;
    Object result = null;
    BufferedReader buffer = null;
    final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
    static public Future<Object> future;

    @SuppressWarnings("unchecked")
    @Override
    protected Object doInBackground(final String... params) {

//      JsonObject res=null;

        future = executor.submit(new Callable<Object>() {
            @Override
            public Object call() throws IOException {

                try {
                    URL url = new URL(urlString + apiName);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    conn.setConnectTimeout(3000);
                    conn.setReadTimeout(15000);
                    conn.setDoInput(true);
                    conn.setDoOutput(true);

                    out = new OutputStreamWriter(conn.getOutputStream());
                    out.write(params[0]);
                    out.flush();
                    out.close(); out=null;

                    buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//          res= GSON.fromJson(buffer, JsonObject.class);
//          result = new Gson().fromJson(res.toString(), Response_Class);


                    result = GSON.fromJson(buffer, Response_Class);
                    buffer.close(); buffer=null;

//          result = new Gson().fromJson(res.toString(), Response_Class);

                } catch (Exception e) {
                    //
                } finally {
                    if (buffer!=null) {
                        try {
                            buffer.close();
                        } catch (Exception e) { //
                        }
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (Exception e) { //
                        }
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                }

                return result;
            }
        });

        try {
            result = future.get(10, TimeUnit.SECONDS);
        } catch (Exception ignored) {
        }
        return result;
    }
}

-和调用方法-

public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
            API_NAME, final String URL) {
        if(isNetworkAvailable()) {
            response = null;
            try {
                Log.e(API_NAME, "url: " + URL);

                Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));

                HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
                        URL);
                response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();

            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

            if (response != null) {
                String x = new Gson().toJson(response);
                Log.e(RESPONSE_CLASS.getSimpleName(), x);
                return response;
            } else {

            }
        }
            return null;
    }

答案 3 :(得分:1)

将来尝试使用GSON库,它将自动为您自动将JSON对象转换为Java对象。这将有助于避免解析复杂的JSON对象或JSON数组。 https://github.com/google/gson