Contents
see List작성일 2016. 08. 18.
AngularJS JSON Parsing 및 $$hashKey 오류 해결
AngularJS에서 객체를 JSON으로 변환하여 Spring 서버로 Ajax 전송할 때 발생하는 $$hashKey 관련 오류를 해결하는 방법입니다.
문제 상황
AngularJS의 ng-repeat 등에서 사용되는 객체에는 $$hashKey라는 내부 속성이 자동으로 추가됩니다. 이 속성이 서버로 전송되면 Jackson 등에서 파싱 오류가 발생할 수 있습니다.
해결 방법
// angular.toJson() 사용 - $$hashKey 자동 제거
angular.toJson(object);
Ajax 요청 시 적용
$http({
method: "POST",
url: "/api/save",
data: angular.toJson(myObject),
headers: {
"Content-Type": "application/json"
}
}).then(function(response) {
console.log("성공");
});
JSON.stringify vs angular.toJson 차이
var obj = {name: "test", $$hashKey: "object:123"};
// JSON.stringify - $$hashKey 포함
JSON.stringify(obj);
// 결과: {"name":"test","$$hashKey":"object:123"}
// angular.toJson - $$hashKey 제외
angular.toJson(obj);
// 결과: {"name":"test"}
ng-repeat에서 track by 사용
<!-- $$hashKey 생성 방지 -->
<li ng-repeat="item in items track by item.id">
{{item.name}}
</li>
<!-- 인덱스로 추적 -->
<li ng-repeat="item in items track by $index">
{{item.name}}
</li>
Spring Controller에서 처리
// Jackson에서 알 수 없는 속성 무시
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDto {
private String name;
// getters, setters
}
// 또는 전역 설정
objectMapper.configure(
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false
);
angular.copy() 사용
// 깊은 복사로 $$hashKey 제거
var cleanObj = angular.copy(originalObj);
// 또는 배열의 경우
var cleanArray = angular.copy(originalArray);
수동으로 $$hashKey 제거
function removeHashKey(obj) {
if (Array.isArray(obj)) {
return obj.map(removeHashKey);
}
if (obj !== null && typeof obj === "object") {
var result = {};
for (var key in obj) {
if (key !== "$$hashKey") {
result[key] = removeHashKey(obj[key]);
}
}
return result;
}
return obj;
}javascript
| No | 작성일 | Title |
|---|---|---|
| 2045 | 2025. 11. 30. | TypeScript 타입 시스템 완벽 가이드 |
| 2044 | 2025. 11. 30. | React 18 새 기능 - Concurrent Features |
| 1864 | 2022. 07. 27. | [vue3] vue3 setup 에서 자식 컴포넌트 메소드(함수) 호출하기 |
| 1848 | 2022. 06. 11. | [ vuejs ] router 데이터 전달방식 |
| 1847 | 2022. 06. 11. | [ vuejs ] this.$router.push 혹은 link-to 를 setup() 에서 구현 |
| 1846 | 2022. 06. 10. | [ vuejs3 , spring-boot ] 웹개발은 어떻게 구성해야 하는가 |
| 1825 | 2022. 05. 24. | [ vuejs ] 부모,자식 요소의 메소드 호출 |
| 1421 | 2018. 12. 06. | [ angualrjs ] ajax header 포함시켜 $http 사용하기 |
| 1381 | 2017. 11. 30. | 문자열을 숫자로 바꾸는 방법 parseInt 와 Number 비교 |
| 1220 | 2017. 03. 28. | [ AngularJs] bootstrap nav dropdown |