Iterate through each element of JSON string in Android and iOS

Introduction

We will assume that we are going to take JSON string as input String and we will look into the process to access each element of JSON String in Android and iOS.

Android

String jsonString = "{\"animal\":\"Lion\", \"bird\":\"Sparrow\"}";
JSONObject jsonObject = new JSONObject(jsonString);
Iterator < ? > keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
String value = jsonObject.getString(key);
// Here we get the value from the JSON String justify;
}

iOS

We convert the JSON string into JSON object using the extension given below

extension String {
func toJSONObject() -> Any? {
guard let data = self.data(using: .utf8, allowLossyConversion: false) else { return nil }
return try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
}
}

We use the above-mentioned extension as below-

let jsonString = "{\"animal\":\"Lion\", \"bird\":\"Sparrow\"}";
if let jsonObject = jsonString.toJSONObject() as? [String: String] {
for (key, value) in jsonObject {
print("\(key) : \(value)")
// Here we get all the keys and values from JSON string
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *