2011-03-20 5 views
0

배열의 값을 플래그하는 방법을 알고 싶습니다. 중복을 제거하고 의 데이터를 Java에 결합하는 방법을 알고 싶습니다. 다음과 같이배열에서 중복을 플래그하는 방법은 무엇입니까?

내가 위도 사용하여 지리적 위치에 대한 기록을 유지하고는 긴 설명이 JSON 배열로 인코딩 :

[{"lon": 0.001, "lat": 0.001, "desc": test}, {"lon": 0.001, "lat": 0.001, "desc": test2}] 

내가 유지하면서 중복 지리적 위치를 제거 할 수 있도록하고 싶습니다 배열의 "desc"부분.

[{"lon": 0.001, "lat": 0.001, "desc": test, test2}] 

편집 :

//Store locPoints from server in JSONArray 
JSONArray jPointsArray = new JSONArray(serverData); 
List<JSONObject> jObjects = new ArrayList<JSONObject>(); 
List<JSONObject> seenObjects = new ArrayList<JSONObject>(); 

for(int i = 0; i < jPointsArray.length(); ++i) 
{ 
jObjects.add(jPointsArray.getJSONObject(i)); 
}   
for (JSONObject obj : jObjects) 
       { 
        //This always returns true 
        if (!seenObjects.contains(obj))// && !seenObjects.contains(obj.get("lon"))) 
        { 

         Log.i("Sucess", "Huzzah!"); 
         seenObjects.add(obj); 
        } 
        else 
        { 
         //merge the 'desc' field in 'obj' with the 'desc' field in 
         JSONObject original = (JSONObject)seenObjects.get(seenObjects.indexOf(obj)); 
         JSONObject update = obj; 
         original.put("desc", original.get("desc") + ", " + update.get("desc")); 
         seenObjects.get(seenObjects.indexOf(obj)).get("desc")); 

        } 
       } 
+0

그래서 질문은 무엇인가, 일요일 할 수있어? 너의 문제는 이미 해결 된 것 같은데, 안 그래? – dmcnelis

+0

@dmcnelis 나는 이것을 실행 가능한 예제로 정렬하려했지만 내 머리를 둥글게하지 않아서 더 좋은 예를 얻을 수 있기를 바랬다. 자바에서. – nhunston

답변

2

당신이 할 수있는 무엇인가 : 이것은 내가 현재 무엇을하고 무엇에만 동작

//assuming that the array you are filtering is called 'myArray' 
List<Object> seenObjects = new ArrayList<Object>(); 
for (Object obj : myArray) { 
    if (! seenObjects.contains(obj)) { 
     seenObjects.add(obj); 
    } 
    else { 
     //merge the 'desc' field in 'obj' with the 'desc' field in 
     //'seenObjects.get(seenObjects.indexOf(obj))' 
    } 
} 

주 객체 당신이 경우 원하는 것을 수행하는 equals()hashCode()의 구현을 비교하는 경우 (귀하의 경우에는 헤이는 '위도'및 '경도'필드 만 고려해야합니다.)

업데이트 :

import java.util.ArrayList; 
import java.util.List; 

import org.json.simple.JSONObject; 
import org.json.simple.JSONValue; 

public class JsonMergeTest { 
    @SuppressWarnings({ "rawtypes", "unchecked" }) 
    public static void main(String[] args) { 
     List<Object> myArray = new ArrayList<Object>(); 
     myArray.add(MyJsonObject.parse("{\"lon\": 0.001, \"lat\": 0.001, \"desc\": \"test\"}")); 
     myArray.add(MyJsonObject.parse("{\"lon\": 0.001, \"lat\": 0.001, \"desc\": \"test2\"}")); 

     List seenObjects = new ArrayList<Object>(); 
     for (Object obj : myArray) { 
      if (! seenObjects.contains(obj)) { 
       seenObjects.add(obj); 
      } 
      else { 
       //merge the 'desc' field in 'obj' with the 'desc' field in the list 
       MyJsonObject original = (MyJsonObject)seenObjects.get(seenObjects.indexOf(obj)); 
       MyJsonObject update = (MyJsonObject)obj; 
       original.put("desc", original.get("desc") + ", " + update.get("desc")); 
      } 
     } 

     for (MyJsonObject obj : (List<MyJsonObject>)seenObjects) { 
      System.out.println(obj.toJSONString()); 
     } 
    } 

    private static class MyJsonObject extends JSONObject { 
     @Override 
     public boolean equals(Object obj) { 
      if (obj == null || ! (obj instanceof MyJsonObject) || ! this.containsKey("lat") || ! this.containsKey("lon")) { 
       return super.equals(obj); 
      } 
      MyJsonObject jsonObj = (MyJsonObject)obj; 
      return this.get("lat").equals(jsonObj.get("lat")) && this.get("lon").equals(jsonObj.get("lon")); 
     } 

     @Override 
     public int hashCode() { 
      if (! this.containsKey("lat") || ! this.containsKey("lon")) { 
       return super.hashCode(); 
      } 
      return this.get("lat").hashCode()^this.get("lon").hashCode(); 
     } 

     @SuppressWarnings("unchecked") 
     public static Object parse(String json) { 
      Object parsedJson = JSONValue.parse(json); 
      if (! (parsedJson instanceof JSONObject)) { 
       return parsedJson; 
      } 

      MyJsonObject result = new MyJsonObject(); 
      result.putAll((JSONObject)parsedJson); 
      return result; 
     } 
    } 
} 
+0

@aroth 이것이 내가 필요로하는 것처럼 보입니다. 컬렉션이기 때문에 seenObject.get (obj)를 어떻게 사용합니까? – nhunston

+0

맞습니다. 병합 작업을 위해 원래 개체를 쉽게 가져올 수 있도록 Set 대신 List를 사용하도록 예제를 업데이트했습니다. – aroth

+0

@aroth이 날을 위해 작동하지 않습니다. 나는 JSONObjects를 사용하고이 if 문을 사용하고 있습니다. if (! seenObjects.contains (obj.get ("lat")) &&! seenObjects.contains (obj.get "lon"))) 하지만 항상 true를 반환합니다. – nhunston

2

당신은 GSon를 사용할 수 있습니다 여기에

어떤 완전한 예제 코드입니다. 그리고 단계를 수행하십시오

1. 비슷한 위치를 병합 코드를 적는다 JSON 문자열

public class Location implements Comparable<Location> { 
    public String lon; 
    public String lat; 
    public String desc; 

    @Override 
    public String toString() { 
     return "<lon: " + lon +", lat: "+ lat +", desc: " + desc +">"; 
    } 

    @Override 
    public boolean equals(Object obj) { 
     return ((Location)obj).lon.equals(lon) && ((Location)obj).lat.equals(lat); 
    } 

    public int compareTo(Location obj) { 
     return ((Location)obj).lon.compareTo(lon) + ((Location)obj).lat.compareTo(lat); 
    } 


} 

2을 매핑, 자바에 상응하는 POJO를 정의합니다. OK, 그것은 그것을 할 :)

public static void main(String[] args){ 
     //Some test data 
    String s = "[" + 
      " {\"lon\": 0.001, \"lat\": 0.001, \"desc\": \"test\"}," + 
      " {\"lon\": 0.002, \"lat\": 0.001, \"desc\": \"test3\"}," + 
      " {\"lon\": 0.002, \"lat\": 0.005, \"desc\": \"test4\"}," + 
      " {\"lon\": 0.002, \"lat\": 0.001, \"desc\": \"test5\"}," + 
      " {\"lon\": 0.001, \"lat\": 0.001, \"desc\": \"test2\"}]"; 
    Gson gson = new Gson(); 
    Location[] al = gson.fromJson(s, Location[].class); 
    List<Location> tl = Arrays.asList(al); 

    //lets sort so that similar locations are grouped 
    Collections.sort(tl); 
    List<Location> fl = new ArrayList<Location>(); 
    Location current = null; 

    //merge! 
    for(Iterator<Location> it = tl.iterator(); it.hasNext();){ 
     current = current==null?it.next():current; 
     Location ltmp = null; 
     while(it.hasNext() && (ltmp = it.next()).equals(current)) 
      current.desc = current.desc + "," + ltmp.desc; 
     fl.add(current); 
     current = ltmp; 
    } 

     //convert back to JSON? 
    System.out.println(gson.toJson(fl)); 

} 

3. 출력

[{"lon":"0.002","lat":"0.005","desc":"test4"}, 
{"lon":"0.002","lat":"0.001","desc":"test3,test5"}, 
{"lon":"0.001","lat":"0.001","desc":"test,test2"}] 
관련 문제