以处理来自HTT presponse的android json的最佳途径途径、presponse、HTT、json

2023-09-07 10:41:46 作者:日久贱人心

我已经使用HttpClient的调用写在Django一个RESTAPI。它返回的JSON输出。我HTT presponse变量保存它和后来的效应初探转换为字符串,然后以JSON对象,我认为它漫长的,虽然这是工作。我真的对Java,有谁能够告诉我,什么是最好的选择逻辑为code以下

 公共无效的onClick(视图v){    // TODO自动生成方法存根    HttpClient的HttpClient的=新DefaultHttpClient();    HTTPGET httppost =新HTTPGET(http://10.0.2.2:8000/api/ca/entry/?            格式= JSON和放大器;用户名= pragya);    尝试{        //添加数据        //列表<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;(2);        //nameValuePairs.add(new BasicNameValuePair(用户名,un.getText()的toString()));        //nameValuePairs.add(new BasicNameValuePair(用户名,pw.getText()的toString()));        //httppost.setEntity(new UrlEn codedFormEntity(namevaluepairs中));        HTT presponse响应= httpclient.execute(httppost);        HttpEntity实体= response.getEntity();        InputStream为= entity.getContent();        读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是));        StringBuilder的SB =新的StringBuilder();        串线= NULL;        尝试{            而((行= reader.readLine())!= NULL){                sb.append((行+\\ n));            }        }赶上(IOException异常五){            e.printStackTrace();        } {最后            尝试{                is.close();            }赶上(IOException异常五){                e.printStackTrace();            }        }        尝试{            的JSONObject的JSONObject =新的JSONObject(sb.toString());            的JSONObject元= jsonObject.getJSONObject(元);            字符串极限= meta.getString(限制);            Toast.makeText(HelloWorldActivity.this,限制Toast.LENGTH_SHORT).show();            JSONArray阵列= jsonObject.getJSONArray(对象);            字符串键= array.getJSONObject(0).getString(API_KEY);            字符串的uname = array.getJSONObject(0).getString(用户名);            Toast.makeText(HelloWorldActivity.this,UNAME ++键,            Toast.LENGTH_SHORT).show();        }赶上(JSONException E){            // TODO自动生成catch块            e.printStackTrace();        }        //Toast.makeText(HelloWorldActivity.this,sb.toString(),Toast.LENGTH_SHORT).show();    }赶上(ClientProtocolException E){        Toast.makeText(HelloWorldActivity.this,e.toString(),Toast.LENGTH_SHORT).show();        // TODO自动生成catch块    }赶上(IOException异常五){        // TODO自动生成catch块        Toast.makeText(HelloWorldActivity.this,e.toString(),Toast.LENGTH_SHORT).show();    }}}); 

的JSON如下:

  {元:{极限:20,下一步:空,抵消:0,previous:空,TOTAL_COUNT:1 },物:[{API_KEY:c87391754b522d0c83b2c8b5e4c8cfd614559632deee70fdf1b48d470307e40e,是homeAddress:加德满都,resource_uri:/ API / CA /项/ 1 /,用户名:SUMIT}]} 

解决方案 SpringMVC中用 ResponseBody返回JSON数据时,NULL字段不进行JSON序列化

使用 GSON 库从谷歌,它是完美的这类任务。

所有你需要做的就是定义一个包含与JSON对象在键的名称字段创建新的类,然后用GSON直接解析JSON字符串转换为对象,反之亦然。

因此​​,例如:

的Json如下:限制:20,下一步:空,抵消:0,previous:空,TOTAL_COUNT:1

Java的类将是:

 公共类MyClass的{    私人诠释限制;    私人诠释下一个;    私人诠释抵消;    私人诠释previous;    私人诠释TOTAL_COUNT;公众诠释getLimit(){    返回限制;}公共无效setLimit(INT限制){    this.limit =限制;}公众诠释GETNEXT(){    返回下一个;}公共无效setNext(INT下一个){    this.next =下一个;}公众诠释的getOffset(){    返回偏移;}公共无效setOffset(INT偏移){    this.offset =偏移;}公众诠释的get previous(){    返回previous;}公共无效集previous(INT previous){    这previous = previous。}公众诠释getTotal_count(){    返回TOTAL_COUNT;}公共无效setTotal_count(INT TOTAL_COUNT){    this.total_count = TOTAL_COUNT;}} 

和使用GSON code这样的:

  GSON GSON =新GSON(); //或者使用新GsonBuilder()创建()。 MyClass的MyClass的= gson.fromJson(JSON,MyClass.class); // JSON反序列化到MyClass的 

请注意,类字段的名称必须完全匹配在键的JSON字符串的名称。

I have used httpclient to call a restapi written in django. It returned the json output. My httpresponse variable stored it and later convert the reponse to string and then to json object, i think its lengthy though it is working . I am really new to java , can anybody advise me , what is the best alternative logic to the code below

public void onClick(View v) {
    // TODO Auto-generated method stub

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httppost = new HttpGet("http://10.0.2.2:8000/api/ca/entry/?
            format=json&username=pragya");
    try {
        // Add your data
        //List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        //nameValuePairs.add(new BasicNameValuePair("username", un.getText().toString()));
        //nameValuePairs.add(new BasicNameValuePair("username", pw.getText().toString()));
        //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            JSONObject jsonObject = new JSONObject(sb.toString());
            JSONObject meta = jsonObject.getJSONObject("meta");  
            String limit = meta.getString("limit");  
            Toast.makeText(HelloWorldActivity.this, limit, Toast.LENGTH_SHORT).show();
            JSONArray array = jsonObject.getJSONArray("objects");

            String key = array.getJSONObject(0).getString("api_key");
            String uname = array.getJSONObject(0).getString("username");
            Toast.makeText(HelloWorldActivity.this, uname + " " + key,
            Toast.LENGTH_SHORT).show();

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        //Toast.makeText(HelloWorldActivity.this, sb.toString(), Toast.LENGTH_SHORT).show();
    } catch (ClientProtocolException e) {
        Toast.makeText(HelloWorldActivity.this, e.toString(), Toast.LENGTH_SHORT).show();

        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Toast.makeText(HelloWorldActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
    }   
}
});

the json is as follows

{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"api_key": "c87391754b522d0c83b2c8b5e4c8cfd614559632deee70fdf1b48d470307e40e", "homeAddress": "kathmandu", "resource_uri": "/api/ca/entry/1/", "username": "sumit"}]}

解决方案

Use Gson library from google, it is perfect for these kind of tasks.

All you need to do is define a new class that contains fields with the names of the keys in the json object and then use Gson to parse the Json string directly into the object or vice versa.

So for example:

Json looks like this: "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1.

Java Class will be:

public class MyClass {
    private int limit;
    private int next;
    private int offset;
    private int previous;
    private int total_count;

public int getLimit() {
    return limit;
}
public void setLimit(int limit) {
    this.limit = limit;
}
public int getNext() {
    return next;
}
public void setNext(int next) {
    this.next = next;
}
public int getOffset() {
    return offset;
}
public void setOffset(int offset) {
    this.offset = offset;
}
public int getPrevious() {
    return previous;
}
public void setPrevious(int previous) {
    this.previous = previous;
}
public int getTotal_count() {
    return total_count;
}
public void setTotal_count(int total_count) {
    this.total_count = total_count;
}
}

And use Gson code like that:

 Gson gson = new Gson(); // Or use new GsonBuilder().create();
 MyClass myClass = gson.fromJson(json, MyClass.class); // deserializes json into MyClass 

Please note that the name of the class fields have to match exactly the name of the keys in the json string.

 
精彩推荐
图片推荐