判断json 是否有重复数据

qq_19347447 2016-05-18 09:41:13
	public static void main(String[] args) throws JSONException {
String data = "[{'goodsId':'11','goodsq':'10'},{'goodsId':'11','goodsq':'10'},{'goodsId':'113','goodsq':'10'},{'goodsId':'112','goodsq':'10'}]";
JSONArray a = new JSONArray(data);
List<String> list = new ArrayList<String>();
for (int i = 0; i < a.length(); i++) {
JSONObject jo = a.getJSONObject(i);
list.add(jo.toString());
}
int count = 0;
for (int i = 0; i < a.length(); i++) {
JSONObject jo = a.getJSONObject(i);
count += list.indexOf(jo.toString());
}

if (count == a.length()) {
System.out.println("没有重复");
} else {
System.out.println("有重复了");
}
}


还有更好的方法吗?
...全文
835 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
include000 2016-05-19
  • 打赏
  • 举报
回复
你建立一个Map的HashMap 往里add不可以么 ,如果你通过goodsId来区分重复那就add goodsId 最后HashMap 剩下的就是不重复的。
Intboy 2016-05-19
  • 打赏
  • 举报
回复
只是判断是否有重复,我觉得可以用二分查找(或者其他查找算法)去找,单纯的for循环遍历效率肯定不高。
bree06 2016-05-19
  • 打赏
  • 举报
回复
如果只是你举例这种简单结构的json可以直接处理字符串没必要转为JSONArray再转为ArrayList.
public static void main(String[] args) {
    String data = "[{'goodsId':'11','goodsq':'10'},{'goodsId':'113','goodsq':'10'},{'goodsId':'112','goodsq':'10'},{'goodsId':'11','goodsq':'10'}]";
    data = data.replace(" ","").substring(1,data.length()-1); // 去掉头尾[]
    int index = 0;
    do {
        int _index = data.indexOf("},{", index);
        // 最后一组不用比较肯定不会有相同的所以直接退出
        if (_index <= -1) {
            break;
        }
        String sub_str = data.substring(index,_index+1);
        if (data.indexOf(sub_str, _index) > _index) {
            System.out.println("有重复数据." + sub_str);
            break;
        }
        index = _index+2;
    } while (true);
}
foo1st 2016-05-18
  • 打赏
  • 举报
回复
使用集合容器,重复记录会添加不进去
qq_19347447 2016-05-18
  • 打赏
  • 举报
回复
。。。 发重复了
	public static void main(String[] args) throws JSONException {
		String data = "[{'goodsId':'11','goodsq':'1023','gg':'1231'},{'goodsId':'11','goodsq':'1023','gg':'1231'},{'goodsId':'11','goodsq':'102','gg':'123'}]";
		JSONArray a = new JSONArray(data);
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < a.length(); i++) {
			JSONObject jo = a.getJSONObject(i);
			String d = returnStr(jo.toString());  // 需要判断  goodsq 以后的 数据重复
			if(list.contains(d)){
				System.out.println("重复了"+d);
			}else{
				list.add(d);
				System.out.println("没有重复"+d);
			}	
			
		}
	}
	
	private static  String returnStr (String srt){
		 int i= srt.indexOf("goodsq");
		 srt=srt.substring(i,srt.length());
		return srt;		
	}

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧