从json字符串android

时间:2017-02-17 17:03:13

标签: java android json

我正在尝试使用Remove duplicates from a Json String in Java?问题的答案从json字符串中删除重复项,但它无效。这是我的代码

inquire.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //location = loc.getText().toString();
            StringRequest request = new StringRequest(Request.Method.POST, urlRec, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        String responseString = response.toString();
                        JSONObject obj = new JSONObjectIgnoreDuplicates(responseString);
                        JSONArray recJsonArray = obj.getJSONArray("search");
                        // JSONArray recJsonArray = new JSONArray(responseString);
                        List<Recipient> recList = new ArrayList<>();
                        for (int i = 0; i < recJsonArray.length(); i++) {
                            JSONObject recJsonObj = (JSONObject) recJsonArray.get(i);
                            Recipient rec = new Recipient();
                            rec.setname(recJsonObj.getString("name"));
                            rec.setLocation(recJsonObj.getString("location"));
                            rec.setcontact(recJsonObj.getString("contact"));
                            recList.add(rec);
                        }
                        Intent myintent = new Intent(Search_inq.this, Reclist.class);
                        myintent.putExtra("recList", (Serializable) recList);
                        startActivity(myintent);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Error", error.getMessage());
                    Toast.makeText(getApplication(), "Error occurred", Toast.LENGTH_LONG).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> parameters = new HashMap<>();
                    parameters.put("location", location);
                    return parameters;
                }
            };
            queue.add(request);
        }
    });

在这里,我进行查询的表格称为SEARCH。如果可以请帮助。

修改

这是JSONObjectIgnoreDuplicates类的代码

public class JSONObjectIgnoreDuplicates extends JSONObject {


    public JSONObjectIgnoreDuplicates(String json) throws JSONException {
        super(json);
    }

    public JSONObject putOnce(String key, Object value) throws JSONException {
        Object storedValue;
        if (key != null && value != null) {
            if ((storedValue = this.opt(key)) != null ) {
                if(!storedValue.equals(value))                          //Only through Exception for different values with same key

                   Log.d("not accepted","n");


                else
                    return this;
            }
            this.put(key, value);
        }
        return this;
    }

}

编辑 -

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

    Intent i = getIntent();
   // List<Recipient> recList = (List<Recipient>) i.getParcelableArrayListExtra("recList");
    ArrayList<Recipient> recList = getIntent().getParcelableArrayListExtra("recList");
    list = (ListView) findViewById(R.id.list1);


    onLoaded(recList);


}

public void onLoaded(List<Recipient> recList) {

    for (Recipient rec : recList) {

        HashMap<String, String> map = new HashMap<>();

        map.put("name", rec.getUserName());
        map.put("location", rec.getLocation());
        map.put("contact", rec.getContact());

        recplist.add(map);
    }

    loadListView();
}

private void loadListView() {

    ListAdapter adapter = new SimpleAdapter(Reclist.this, recplist, R.layout.list_item,
            new String[]{"name", "location", "contact"},
            new int[]{R.id.textView3, R.id.textView4, R.id.textView6});

    list.setAdapter(adapter);
}

1 个答案:

答案 0 :(得分:0)

为您的Recipient类创建一个等于和哈希码的覆盖,并且在它的同时使它实现Parcelable,因为它比可序列化更快。例如:

public class Recipient implements Parcelable {
    private String name, location, contact;

    public Recipient(String name, String location, String contact) {
        this.name = name;
        this.location = location;
        this.contact = contact;
    }

    public String getName() {
        return name;
    }

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

    public String getLocation() {
        return location;
    }

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

    public String getContact() {
        return contact;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Recipient recipient = (Recipient) o;

        if (name != null ? !name.equals(recipient.name) : recipient.name != null) return false;
        if (location != null ? !location.equals(recipient.location) : recipient.location != null)
            return false;
        return contact != null ? contact.equals(recipient.contact) : recipient.contact == null;

    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (location != null ? location.hashCode() : 0);
        result = 31 * result + (contact != null ? contact.hashCode() : 0);
        return result;
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.name);
        dest.writeString(this.location);
        dest.writeString(this.contact);
    }

    protected Recipient(Parcel in) {
        this.name = in.readString();
        this.location = in.readString();
        this.contact = in.readString();
    }

    public static final Parcelable.Creator<Recipient> CREATOR = new Parcelable.Creator<Recipient>() {
        @Override
        public Recipient createFromParcel(Parcel source) {
            return new Recipient(source);
        }

        @Override
        public Recipient[] newArray(int size) {
            return new Recipient[size];
        }
    };
}

然后您的实现可以如下,因为Recipient类可以通过ArrayList#contains方法进行比较:

try {
    String responseString = response.toString();
    JSONObject object = new JSONObject(responseString);
    JSONArray recJsonArray = object.getJSONArray("search");

    ArrayList<Recipient> recList = new ArrayList<>();
    for (int i = 0; i < recJsonArray.length(); i++) {
        JSONObject recJsonObj = (JSONObject) recJsonArray.get(i);
        Recipient rec = new Recipient(recJsonObj.getString("name"),
                                      recJsonObj.getString("location"),
                                      recJsonObj.getString("contact"));
        if (!recList.contains(rec)) {
            // if it isn't already there, add it
            recList.add(rec);
        }
    }
    Intent myintent = new Intent(Search_inq.this, Reclist.class);
    //use putParcelableArrayListExtra since its faster than serializable
    myintent.putParcelableArrayListExtra("recList", recList);
    startActivity(myintent);
} catch (JSONException e) {
    Log.e("some tag", e.getMessage(), e);
}

要从新活动中使用意图中获取数据:

ArrayList<Recipient> recList = getIntent().getParcelableArrayListExtra("recList");