Ich verwende eine JSON-Bibliothek mit dem Namen JSONObject
(es macht mir nichts aus, wenn ich es brauche).
Ich weiß, wie man JSONArrays
durchläuft, aber wenn ich JSON-Daten von Facebook parse, bekomme ich kein Array, sondern nur eine JSONObject
, aber ich muss über seinen Index auf ein Element zugreifen können, wie JSONObject[0]
, um das erste zu erhalten und ich kann nicht herausfinden, wie es geht.
{
"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
}
}
Vielleicht hilft das:
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
}
}
für meinen Fall fand ich das Iterieren der names()
gut funktioniert
for(int i = 0; i<jobject.names().length(); i++){
Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i)));
}
Ich werde den Iterator vermeiden, da er Objekte während der Iteration hinzufügen/entfernen kann, und auch für sauberen Code eine for-Schleife verwenden kann. weniger Zeile einfacher Code.
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);
}
}
Ich kann nicht glauben, dass es keine einfachere und sicherere Lösung gibt als einen Iterator ...
Die JSONObject names ()
-Methode gibt ein JSONArray der JSONObject-Schlüssel zurück, sodass Sie sie einfach in einer Schleife durchlaufen können:
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");
}
Füge dies zuerst irgendwo ein:
private <T> Iterable<T> iteratorToIterable(final Iterator<T> iterator) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return iterator;
}
};
}
Oder wenn Sie Zugriff auf Java8 haben, einfach Folgendes:
private <T> Iterable<T> iteratorToIterable(Iterator<T> iterator) {
return () -> iterator;
}
Dann iterieren Sie einfach die Schlüssel und Werte des Objekts:
for (String key : iteratorToIterable(object.keys())) {
JSONObject entry = object.getJSONObject(key);
// ...
org.json.JSONObject verfügt jetzt über eine keySet () - Methode, die einen Set<String>
zurückgibt und mit einem for-each leicht durchlaufen werden kann.
for(String key : jsonObject.keySet())
Ich habe eine kleine rekursive Funktion erstellt, die das gesamte Json-Objekt durchläuft und den Schlüsselpfad und seinen Wert speichert.
// 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();
}
}
Mit Java 8 und Lambda Reiniger:
JSONObject jObject = new JSONObject(contents.trim());
jObject.keys().forEachRemaining(k ->
{
});
Der folgende Code hat für mich gut funktioniert. Bitte helfen Sie mir, wenn Sie das Tuning durchführen können. Dadurch werden alle Schlüssel auch von den geschachtelten JSON-Objekten abgerufen.
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;
}
Ich hatte einmal einen Json, dessen IDs um eins erhöht werden mussten, da sie 0-indexiert waren und das automatische Inkrementieren von MySQL brach.
Also für jedes Objekt, das ich diesen Code geschrieben habe - könnte es jemandem helfen:
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);
}
}
}
}
}
verwendungszweck:
JSONObject object = ....
incrementValue(object, Arrays.asList("id", "product_id", "category_id", "customer_id"));
dies kann für JSONArray auch als übergeordnetes Objekt verwendet werden
Wir haben einen Satz von Code verwendet, um JSONObject
-Felder zu durchlaufen
Iterator iterator = jsonObject.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, JsonElement> entry = (Entry<String, JsonElement>) iterator.next();
processedJsonObject.add(entry.getKey(), entry.getValue());
}