org.json을 복제하려면 어떻게 해야 하나요?Java의 JSONObject?
의 인스턴스를 복제하는 방법이 있습니까?org.json.JSONObject
그 결과를 왜곡하거나 재구성하지 않고요?
얄팍한 카피라도 괜찮습니다.
가장 쉬운 방법(또한 매우 느리고 비효율적)
JSONObject clone = new JSONObject(original.toString());
생성자 및 메서드를 사용합니다.
JSONObject copy = new JSONObject(original, JSONObject.getNames(original));
원인$JSONObject.getNames(original)
Android에서는 액세스 할 수 없습니다.다음으로 할 수 있습니다.
public JSONObject shallowCopy(JSONObject original) {
JSONObject copy = new JSONObject();
for ( Iterator<String> iterator = original.keys(); iterator.hasNext(); ) {
String key = iterator.next();
JSONObject value = original.optJSONObject(key);
try {
copy.put(key, value);
} catch ( JSONException e ) {
//TODO process exception
}
}
return copy;
}
그러나 이것은 깊은 복사가 아니라는 것을 기억하라.
Android 개발자에게 있어, 를 사용하지 않는 가장 간단한 솔루션.getNames
다음과 같습니다.
JSONObject copy = new JSONObject();
for (Object key : original.keySet()) {
Object value = original.get(key);
copy.put(key, value);
}
주의: 이것은 얕은 복사입니다.
제가 찾은 가장 빠른 + 최소한의 방법은 이것입니다.딥 카피를 합니다.
JSONObject clone= new JSONObject(original.toMap());
질문자가 말한 거 알아요.
얄팍한 카피라도 괜찮습니다.하지만 이 솔루션이 딥 카피를 할 수 있을지는 배제되지 않는다고 생각합니다.
업데이트: Android에서는 toMap() 함수를 사용할 수 없습니다.단, groupId org.json의 maven에서 이용할 수 있는 org.json 라이브러리는 다음과 같습니다.https://search.maven.org/artifact/org.json/json/20210307/bundle
com.google.gwt.json.client의 기존 딥 클론 메서드를 찾을 수 없습니다.JSONObject 단, 구현은 다음과 같은 몇 줄의 코드여야 합니다.
public static JSONValue deepClone(JSONValue jsonValue){
JSONString string = jsonValue.isString();
if (string != null){return new JSONString(string.stringValue());}
JSONBoolean aBoolean = jsonValue.isBoolean();
if (aBoolean != null){return JSONBoolean.getInstance(aBoolean.booleanValue());}
JSONNull aNull = jsonValue.isNull();
if (aNull != null){return JSONNull.getInstance();}
JSONNumber number = jsonValue.isNumber();
if (number!=null){return new JSONNumber(number.doubleValue());}
JSONObject jsonObject = jsonValue.isObject();
if (jsonObject!=null){
JSONObject clonedObject = new JSONObject();
for (String key : jsonObject.keySet()){
clonedObject.put(key, deepClone(jsonObject.get(key)));
}
return clonedObject;
}
JSONArray array = jsonValue.isArray();
if (array != null){
JSONArray clonedArray = new JSONArray();
for (int i=0 ; i < array.size() ; ++i){
clonedArray.set(i, deepClone(array.get(i)));
}
return clonedArray;
}
throw new IllegalStateException();
}
*주의:* 아직 테스트하지 않았습니다!
org.google.gson의 딥 클론을 찾는 사람이 있을 경우를 대비해서 deepClone() 메서드를 공개하지 않기 때문에 제가 생각해낸 것은...
public static JsonElement deepClone(JsonElement el){
if (el.isJsonPrimitive() || el.isJsonNull())
return el;
if (el.isJsonArray()) {
JsonArray array = new JsonArray();
for(JsonElement arrayEl: el.getAsJsonArray())
array.add(deepClone(arrayEl));
return array;
}
if(el.isJsonObject()) {
JsonObject obj = new JsonObject();
for (Map.Entry<String, JsonElement> entry : el.getAsJsonObject().entrySet()) {
obj.add(entry.getKey(), deepClone(entry.getValue()));
}
return obj;
}
throw new IllegalArgumentException("JsonElement type " + el.getClass().getName());
}
다음으로 2개의 Json Object를 Marge하는 몇 가지 방법을 제시하겠습니다.
public static JsonObject merge(String overrideJson, JsonObject defaultObj) {
return mergeInto((JsonObject)new JsonParser().parse(overrideJson), defaultObj);
}
public static JsonObject merge(JsonObject overrideObj, JsonObject defaultObj) {
return mergeOverride((JsonObject)deepClone(defaultObj), overrideObj);
}
public static JsonObject mergeOverride(JsonObject targetObj, JsonObject overrideObj) {
for (Map.Entry<String, JsonElement> entry : overrideObj.entrySet())
targetObj.add(entry.getKey(), deepClone(entry.getValue()));
return targetObj;
}
public static JsonObject mergeInto(JsonObject targetObj, JsonObject defaultObj) {
for (Map.Entry<String, JsonElement> entry : defaultObj.entrySet()) {
if (targetObj.has(entry.getKey()) == false)
targetObj.add(entry.getKey(), deepClone(entry.getValue()));
}
return targetObj;
}
언급URL : https://stackoverflow.com/questions/12809779/how-do-i-clone-an-org-json-jsonobject-in-java
'programing' 카테고리의 다른 글
프로파일이 있는 임베디드 Tomcat의 스프링 부트 활성화/비활성화 (0) | 2023.02.28 |
---|---|
스프링 주석 @ConditionalOnMissingBean의 역할은 무엇입니까? (0) | 2023.02.28 |
ES6/ES7 구문을 사용하여 jQuery UI를 가져오려면 어떻게 해야 합니까? (0) | 2023.02.28 |
타임스탬프에 가장 적합한 Mongoose 스키마 타입 (0) | 2023.02.28 |
인증 유형 10이 지원되지 않아 Postgres DB에 연결할 수 없습니다. (0) | 2023.02.28 |