Parse an entire JSON array into a table using 1 key - json

I need some help with parsing JSON in Swift.
[{"Database":"information_schema"}
{"Database":"Tonysnasa"},
{"Database":"camaleonsystems"},
{"Database":"camaleonsystems_back"},
{"Database":"camaleonsystemsfortest"}]
^ - Above is my JSON
v - Below is my Swift code.
let jsonDB: String! = jsonResult[0]["Database"] as NSString
println(jsonDB)
self.DBList.append(jsonDB)
I want to parse all of the "Database:" entries. When I try the method above, I am only able to parse information_schema.
How can I parse all the "Database:"'s into my table?

looks like it is an array of dictionaries,to get them all you should be able to use:
var jsonDB : [Dictionary<String, String>] = jsonResult
for currentDictionary in jsonDB{
var currentEntry = currentDictionary["Database"] as String
println(currentEntry)
self.DBList.append(currentEntry)
}

Related

Swifty JSON Response Parsing

I am using SwiftyJson. I am getting a response from printing.
{ "coin" : 120 }
I want to store this response in a variable. How can I store this value in a variable?
To get the specific value from response, it's related with type of response.
https://grokswift.com/json-swift-4/
For example, if response is JSON Array, Please try this.
let val = response[index][key]
otherwise,
let val = response[key1][key2][..]

change JSON to String in Swift [duplicate]

This question already has answers here:
Simple and clean way to convert JSON string to Object in Swift
(17 answers)
Closed 5 years ago.
I got JSON file from API but the content looks like this:
[
"https:\/\/seekingalpha.com\/article\/4125943-apple-homepod-delay-big-deal?source=feed_symbol_AAPL"
]
Suppose the JSON Object above is named as json. Then I just convert the object to string using String() method.
strings = String(json)
When I changed it to String type, it seems to get unnecessary '\n' and whitespace in it.
"[\n \"https:\\/\\/seekingalpha.com\\/article\\/4125943-apple-homepod-delay-big-deal?source=feed_symbol_AAPL\"\n]"
So it seems like the content of the JSON file is:
["\n""whitespace""whitespace""String""\n"]
When I changed it to String type, Swift just treats all the elements in it as a whole and wrapped it as a string.
My question is, how to extract the String inside so it looks like:
"https:\\/\\/seekingalpha.com\\/article\\/4125943-apple-homepod-delay-big-deal?source=feed_symbol_AAPL\"
As I am not so familiar with Swift so how to extract String or JSON Object is not easy for me. Any hints or help will be appreciated.
Swift 3,4 :
The given JSON format is Array of String.
if let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String]{
let firstElement = json?.first ?? "Element Not Found!"
print(firstElement)
}
Swift 4:
if let json = try? JSONDecoder().decode(Array<String>.self, from: data){
let firstElement = json.first ?? "First Element Not Found!"
print(firstElement)
}
Note:
If your the Array contains more than one String. Here,urls is the class variable. i.e.,var urls = [String]()
Swift 3,4 :
if let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String]{
if json != nil{
self.urls = json!
}
print(self.urls)
}
Swift 4:
if let json = try? JSONDecoder().decode(Array<String>.self, from: data){
self.urls = json
}
1. You will first have to convert JSON to Data
2. Convert data to string wrt to encoding
func jsonToString(jsonTOConvert: AnyObject){
do {
let data = try JSONSerialization.data(withJSONObject: jsonTOConvert, options: JSONSerialization.WritingOptions.prettyPrinted)
let convertedString = String(data: data, encoding: String.Encoding.utf8)
} catch let myJSONError {
print(myJSONError)
}
}
You are asking that a String be created with the contents:
[
"https:\/\/seekingalpha.com\/article\/4125943-apple-homepod-delay-big-deal?source=feed_symbol_AAPL"
]
The string object is doing exactly what you told it to — the thing you've asked it to represent begins with a square bracket, then there's a line break, then two spaces, etc, so the string contains a square bracket, then a line break, then two spaces, etc. There is no 'unnecessary' \n, there is only the \n you told it to put in.
If you obtained a JSON object then you need to parse it as JSON. JSONSerialization will do that job. What you've actually got is an array with a single item, which is a string. So JSONSerialization will return an array. The first item of that should be a string that is the seekingalpha.com URL.

Couchbase - deserialize json into dynamic type

I'm trying to deserialize some JSON coming back from couchbase into a dynamic type.
The document is something like this so creating a POCO for this would be overkill:
{
UsersOnline: 1
}
I figured that something like this would do the trick, but it seems to deserialize into a dynamic object with the value just being the original JSON
var jsonObj = _client.GetJson<dynamic>(storageKey);
results in:
jsonObj { "online": 0 }
Is there anyway I can get the couchbase deserializer to generate the dynamic type for me?
Cheers
The default deserializer for the client uses .NET's binary serializer, so when you save or read a JSON string, it's just a string. GetJson will always just return a string. However, there are a couple of options:
You could convert JSON records to Dictionary instances:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
var item = client.GetJson<Dictionary<string, object>>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item["UsersOnline"], item["NewestMember"]);
Or you could use a dynamic ExpandoObject instance:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
dynamic item = client.GetJson<ExpandoObject>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item.UsersOnline, item.NewestMember);
In either case you're losing static type checking, which seems like it's OK for your purposes. In both cases you get access to the JSON properties without having to parse the JSON into a POCO though...
Edit: I wrote a couple of extension methods that may be useful and blogged about them at http://blog.couchbase.com/moving-no-schema-stack-c-and-dynamic-types

json parse returning null

i am trying to parse some json for the first time. My json looks like this:
{"categoryid":"2","accountid":"1","title":"Bed for sale","price":"2.99","description":"brand new bed ....}]
I've been trying to follow this tutorial:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
However, his JSON looks like:
{"paging":{"page":1,"total":123,"page_size":20,"pages":7},"loans":[{"id":519535,"name":"Oyunbat","description":{"languages": ....
The code in the tutorial expects the objectID "loans" however the JSON i'm attempting to parse does not have this objectID. It just has the value/key pairs.
My problem seems to be with this part of the code:
NSArray* latestLoans = [json objectForKey:#"title"];
Where the dictionary is placed into an array. But since i do not have this objectID in my JSON i am getting a null returned and no data.
How can i do just a simple parse of the JSON i have by putting into an array?
Thank you very much for any help! I'm new to this and trying to get going.
Looks like a root and child. Try this:
dict = [resp objectForKey:#"paging"];
if( ( dict == nil ) || ![dict isKindOfClass:[NSDictionary class]] ) {
NSLog( #"WARNING: %#", [dict description]);
return;
}
Title = [[dict objectForKey:#"title"]copy];
NSLog(#"Your Value: %#", Title);

Parse JSON string - ios sdk

{"aps":{
"alert":"New Test For The Win",
"sound":"default"
},
"fk_device":"1513"
}
I have this JSON NSString. How can I parse this JSON string and get fk_device value?
You can try this library JSONKit. To get the string, you can do something like this:
NSDictionary *deserializedData = [jsonString objectFromJSONString];
NSString *string = [deserializedData objectForKey:#"fk_device"];