JSONObject를 반복하는 방법
JSON 라이브러리를 사용하고 있습니다.JSONObject
(필요하다면 바꿔도 상관없습니다).
나는 반복할 줄 안다.JSONArrays
단, Facebook에서 JSON 데이터를 해석하면 어레이가 표시되지 않고JSONObject
단, 다음과 같은 인덱스를 통해 항목에 액세스할 수 있어야 합니다.JSONObject[0]
어떻게 해야 할지 모르겠어요
{
"http://http://url.com/": {
"id": "http://http://url.com//"
},
"http://url2.co/": {
"id": "http://url2.com//",
"shares": 16
}
,
"http://url3.com/": {
"id": "http://url3.com//",
"shares": 16
}
}
이 방법이 도움이 될 수 있습니다.
JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
// do something with jsonObject here
}
}
내 경우, 나는 반복하는 것을 알았다.names()
잘 동작하다
for(int i = 0; i<jobject.names().length(); i++){
Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i)));
}
반복 시 오브젝트를 추가/삭제할 수 있고 루프용 클린코드도 사용할 수 있기 때문에 반복자는 피하겠습니다.깔끔하고 줄이 적어집니다.
Java 8 및 Lamda 사용 [2019년 4월 2일 업데이트]
import org.json.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
jsonObj.keySet().forEach(keyStr ->
{
Object keyvalue = jsonObj.get(keyStr);
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
//if (keyvalue instanceof JSONObject)
// printJsonObject((JSONObject)keyvalue);
});
}
기존 방식 사용 [Update 4/2/2019]
import org.json.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
for (String keyStr : jsonObj.keySet()) {
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
//if (keyvalue instanceof JSONObject)
// printJsonObject((JSONObject)keyvalue);
}
}
원답
import org.json.simple.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
if (keyvalue instanceof JSONObject)
printJsonObject((JSONObject)keyvalue);
}
}
이 답변에 반복기를 사용하는 것보다 더 간단하고 안전한 솔루션은 없다니 믿을 수 없습니다.
JSONObjectnames ()
메서드는 a를 반환합니다.JSONArray
의JSONObject
키를 누르면 루프를 따라 걸을 수 있습니다.
JSONObject object = new JSONObject ();
JSONArray keys = object.names ();
for (int i = 0; i < keys.length (); i++) {
String key = keys.getString (i); // Here's your key
String value = object.getString (key); // Here's your value
}
Iterator<JSONObject> iterator = jsonObject.values().iterator();
while (iterator.hasNext()) {
jsonChildObject = iterator.next();
// Do whatever you want with jsonChildObject
String id = (String) jsonChildObject.get("id");
}
org.json.이제 JSONObject는 keySet() 메서드를 사용하여Set<String>
각각을 위한 루프로 쉽게 연결할 수 있습니다.
for(String key : jsonObject.keySet())
이 답변의 대부분은 플랫 JSON 구조에 대한 것입니다. JSON이 중첩된 JSONArray 또는 중첩된 JSONObjects일 수 있는 경우 실제 복잡성이 발생합니다.다음 코드 조각은 이러한 비즈니스 요구사항을 처리합니다.해시 맵과 네스트된 JSONAray와 JSONObject를 모두 가진 계층형 JSON을 사용하여 해시 맵 내의 데이터를 사용하여 JSON을 업데이트합니다.
public void updateData(JSONObject fullResponse, HashMap<String, String> mapToUpdate) {
fullResponse.keySet().forEach(keyStr -> {
Object keyvalue = fullResponse.get(keyStr);
if (keyvalue instanceof JSONArray) {
updateData(((JSONArray) keyvalue).getJSONObject(0), mapToUpdate);
} else if (keyvalue instanceof JSONObject) {
updateData((JSONObject) keyvalue, mapToUpdate);
} else {
// System.out.println("key: " + keyStr + " value: " + keyvalue);
if (mapToUpdate.containsKey(keyStr)) {
fullResponse.put(keyStr, mapToUpdate.get(keyStr));
}
}
});
}
여기서 이 반환 유형은 무효이지만 이 변경이 발신자에게 재지정될 때 sice 객체가 전달됩니다.
우선 이것을 어디에 두어라:
private <T> Iterable<T> iteratorToIterable(final Iterator<T> iterator) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return iterator;
}
};
}
Java8 에 액세스 할 수 있는 경우는, 다음과 같습니다.
private <T> Iterable<T> iteratorToIterable(Iterator<T> iterator) {
return () -> iterator;
}
그런 다음 오브젝트의 키와 값을 반복하기만 하면 됩니다.
for (String key : iteratorToIterable(object.keys())) {
JSONObject entry = object.getJSONObject(key);
// ...
json 객체 전체를 통해 키 경로와 값을 저장하는 작은 재귀 함수를 만들었습니다.
// My stored keys and values from the json object
HashMap<String,String> myKeyValues = new HashMap<String,String>();
// Used for constructing the path to the key in the json object
Stack<String> key_path = new Stack<String>();
// Recursive function that goes through a json object and stores
// its key and values in the hashmap
private void loadJson(JSONObject json){
Iterator<?> json_keys = json.keys();
while( json_keys.hasNext() ){
String json_key = (String)json_keys.next();
try{
key_path.push(json_key);
loadJson(json.getJSONObject(json_key));
}catch (JSONException e){
// Build the path to the key
String key = "";
for(String sub_key: key_path){
key += sub_key+".";
}
key = key.substring(0,key.length()-1);
System.out.println(key+": "+json.getString(json_key));
key_path.pop();
myKeyValues.put(key, json.getString(json_key));
}
}
if(key_path.size() > 0){
key_path.pop();
}
}
Java 8 및 lamda를 사용하면 더 깨끗해집니다.
JSONObject jObject = new JSONObject(contents.trim());
jObject.keys().forEachRemaining(k ->
{
});
아래 코드 세트를 사용하여 반복했습니다.JSONObject
필드
Iterator iterator = jsonObject.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, JsonElement> entry = (Entry<String, JsonElement>) iterator.next();
processedJsonObject.add(entry.getKey(), entry.getValue());
}
저는 한때 0-indexed이기 때문에 1씩 증가해야 하는 ID를 가진 json을 가지고 있었는데, 그것은 Mysql 자동 증가를 방해하고 있었습니다.
각 오브젝트에 대해 이 코드를 작성했습니다.다른 사람에게 도움이 될 수 있습니다.
public static void incrementValue(JSONObject obj, List<String> keysToIncrementValue) {
Set<String> keys = obj.keySet();
for (String key : keys) {
Object ob = obj.get(key);
if (keysToIncrementValue.contains(key)) {
obj.put(key, (Integer)obj.get(key) + 1);
}
if (ob instanceof JSONObject) {
incrementValue((JSONObject) ob, keysToIncrementValue);
}
else if (ob instanceof JSONArray) {
JSONArray arr = (JSONArray) ob;
for (int i=0; i < arr.length(); i++) {
Object arrObj = arr.get(0);
if (arrObj instanceof JSONObject) {
incrementValue((JSONObject) arrObj, keysToIncrementValue);
}
}
}
}
}
사용방법:
JSONObject object = ....
incrementValue(object, Arrays.asList("id", "product_id", "category_id", "customer_id"));
이것은 JSONArray에서도 상위 객체로 작동하도록 변환될 수 있습니다.
JsonObject 필드를 기록하고 몇 가지 찌르는 방법을 만들었습니다.유용하게 쓸 수 있는지 알아보세요.
object JsonParser {
val TAG = "JsonParser"
/**
* parse json object
* @param objJson
* @return Map<String, String>
* @throws JSONException
*/
@Throws(JSONException::class)
fun parseJson(objJson: Any?): Map<String, String> {
val map = HashMap<String, String>()
// If obj is a json array
if (objJson is JSONArray) {
for (i in 0 until objJson.length()) {
parseJson(objJson[i])
}
} else if (objJson is JSONObject) {
val it: Iterator<*> = objJson.keys()
while (it.hasNext()) {
val key = it.next().toString()
// If you get an array
when (val jobject = objJson[key]) {
is JSONArray -> {
Log.e(TAG, " JSONArray: $jobject")
parseJson(jobject)
}
is JSONObject -> {
Log.e(TAG, " JSONObject: $jobject")
parseJson(jobject)
}
else -> {
Log.e(TAG, " adding to map: $key $jobject")
map[key] = jobject.toString()
}
}
}
}
return map
}
}
아래 코드는 문제없이 작동했습니다.튜닝이 가능하다면 도와주세요.그러면 네스트된 JSON 개체에서도 모든 키가 취득됩니다.
public static void main(String args[]) {
String s = ""; // Sample JSON to be parsed
JSONParser parser = new JSONParser();
JSONObject obj = null;
try {
obj = (JSONObject) parser.parse(s);
@SuppressWarnings("unchecked")
List<String> parameterKeys = new ArrayList<String>(obj.keySet());
List<String> result = null;
List<String> keys = new ArrayList<>();
for (String str : parameterKeys) {
keys.add(str);
result = this.addNestedKeys(obj, keys, str);
}
System.out.println(result.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
public static List<String> addNestedKeys(JSONObject obj, List<String> keys, String key) {
if (isNestedJsonAnArray(obj.get(key))) {
JSONArray array = (JSONArray) obj.get(key);
for (int i = 0; i < array.length(); i++) {
try {
JSONObject arrayObj = (JSONObject) array.get(i);
List<String> list = new ArrayList<>(arrayObj.keySet());
for (String s : list) {
putNestedKeysToList(keys, key, s);
addNestedKeys(arrayObj, keys, s);
}
} catch (JSONException e) {
LOG.error("", e);
}
}
} else if (isNestedJsonAnObject(obj.get(key))) {
JSONObject arrayObj = (JSONObject) obj.get(key);
List<String> nestedKeys = new ArrayList<>(arrayObj.keySet());
for (String s : nestedKeys) {
putNestedKeysToList(keys, key, s);
addNestedKeys(arrayObj, keys, s);
}
}
return keys;
}
private static void putNestedKeysToList(List<String> keys, String key, String s) {
if (!keys.contains(key + Constants.JSON_KEY_SPLITTER + s)) {
keys.add(key + Constants.JSON_KEY_SPLITTER + s);
}
}
private static boolean isNestedJsonAnObject(Object object) {
boolean bool = false;
if (object instanceof JSONObject) {
bool = true;
}
return bool;
}
private static boolean isNestedJsonAnArray(Object object) {
boolean bool = false;
if (object instanceof JSONArray) {
bool = true;
}
return bool;
}
이것은 이 문제에 대한 또 다른 유효한 해결책입니다.
public void test (){
Map<String, String> keyValueStore = new HasMap<>();
Stack<String> keyPath = new Stack();
JSONObject json = new JSONObject("thisYourJsonObject");
keyValueStore = getAllXpathAndValueFromJsonObject(json, keyValueStore, keyPath);
for(Map.Entry<String, String> map : keyValueStore.entrySet()) {
System.out.println(map.getKey() + ":" + map.getValue());
}
}
public Map<String, String> getAllXpathAndValueFromJsonObject(JSONObject json, Map<String, String> keyValueStore, Stack<String> keyPath) {
Set<String> jsonKeys = json.keySet();
for (Object keyO : jsonKeys) {
String key = (String) keyO;
keyPath.push(key);
Object object = json.get(key);
if (object instanceof JSONObject) {
getAllXpathAndValueFromJsonObject((JSONObject) object, keyValueStore, keyPath);
}
if (object instanceof JSONArray) {
doJsonArray((JSONArray) object, keyPath, keyValueStore, json, key);
}
if (object instanceof String || object instanceof Boolean || object.equals(null)) {
String keyStr = "";
for (String keySub : keyPath) {
keyStr += keySub + ".";
}
keyStr = keyStr.substring(0, keyStr.length() - 1);
keyPath.pop();
keyValueStore.put(keyStr, json.get(key).toString());
}
}
if (keyPath.size() > 0) {
keyPath.pop();
}
return keyValueStore;
}
public void doJsonArray(JSONArray object, Stack<String> keyPath, Map<String, String> keyValueStore, JSONObject json,
String key) {
JSONArray arr = (JSONArray) object;
for (int i = 0; i < arr.length(); i++) {
keyPath.push(Integer.toString(i));
Object obj = arr.get(i);
if (obj instanceof JSONObject) {
getAllXpathAndValueFromJsonObject((JSONObject) obj, keyValueStore, keyPath);
}
if (obj instanceof JSONArray) {
doJsonArray((JSONArray) obj, keyPath, keyValueStore, json, key);
}
if (obj instanceof String || obj instanceof Boolean || obj.equals(null)) {
String keyStr = "";
for (String keySub : keyPath) {
keyStr += keySub + ".";
}
keyStr = keyStr.substring(0, keyStr.length() - 1);
keyPath.pop();
keyValueStore.put(keyStr , json.get(key).toString());
}
}
if (keyPath.size() > 0) {
keyPath.pop();
}
}
보다 간단한 접근방식은 다음과 같습니다(W3Schools에서 확인).
let data = {.....}; // JSON Object
for(let d in data){
console.log(d); // It gives you property name
console.log(data[d]); // And this gives you its value
}
갱신하다
이 접근방식은 네스트된 오브젝트를 처리할 때까지 정상적으로 동작하기 때문에 이 접근방식은 동작합니다.
const iterateJSON = (jsonObject, output = {}) => {
for (let d in jsonObject) {
if (typeof jsonObject[d] === "string") {
output[d] = jsonObject[d];
}
if (typeof jsonObject[d] === "object") {
output[d] = iterateJSON(jsonObject[d]);
}
}
return output;
}
그리고 이런 방법을 사용한다.
let output = iterateJSON(your_json_object);
언급URL : https://stackoverflow.com/questions/9151619/how-to-iterate-over-a-jsonobject
'programing' 카테고리의 다른 글
vuex에서 getter의 특별한 용도는 무엇입니까? (0) | 2022.07.02 |
---|---|
Vuex getter의 v-if (0) | 2022.07.01 |
"std"에 "std"가 포함되지 않고 C에서 무엇을 할 수 있습니까?'C'의 일부일까요, 아니면 그냥 라이브러리일까요? (0) | 2022.07.01 |
매개 변수를 사용하여 실행할 수 있습니까? (0) | 2022.07.01 |
Axios 매개 변수가 URL에 올바르게 추가되지 않음 (0) | 2022.07.01 |