Parsing multiple json objects from signle nsstring variable - ios

I know how to parse json object from NSString using NSData and NSDictionary, but I didn't find how to parse multiple json object if I get message like this:
{
"msg_type" : "fist_json",
"field" : "param"
}
{ "second_json_field": [
{
"name_picture": "0.png",
"data_picture":"something"
},
{
"data_values": "something"
} ]
}
{
"third_msg" : "hello"
}

It's not valid JSON, so you can't parse it. A JSON document is either a single array, or a single object (dictionary). Three objects are not valid JSON. You could put square brackets around everything, put commas in the right places, and parse it, getting an array back. Finding the places for the commas without writing a full-blown JSON parser is tricky.
If this is what the server gave you, ask the server people to fix their broken server. If your code for some reason combined three JSON messages into one, then don't do that.

I'm guessing this is not possible in one go. Your provided example text might look like JSON, but it isn't (valid).
I think the service that serves you this response should be 'fixed'.

Related

What is the use of Data Model while API Parsing in swift

Why we should use Data model while parsing API. whereas we can simply get response in the ViewController class it self.
Can someone tell me why we should use Data Model to parse api response..
Thanks in advance
Imagine that you have below json response from server after calling an API:
{
"settings": {
"isUserActive": false,
"isUserAdmin": false,
"rollNumber": 10,
"userId": 2,
"userName": "John"
},
"status": 200,
"message": "Success"
}
Now how will you access the value if you are not using data model. It will be like
let name = response["settings"]["userName"]
(Assuming that you have converted the json into dictionary)
1) What if you have to use the username at multiple place, then you have to do the same thing again.
2) The above json response is simple so it will be easy to get a particular value, but imagine a json where there are nested objects, trying to retrieve a value manually can be pain.
3) If you are working in a team there is a probability that some developers can misspell the key and it can take hours to debug.
Using data model the compiler will throw error if the property is misspelled avoiding bugs.
4) You will have to typecast every time you retrieve the data from dictionary.
When using data models, need to do typecasting only once ie. when parsing the json.
All this pain can be avoided simply using data model, you only have to parse the json once and you can simply use the key as property to access value.
For example see the settings json, once you parse it to data model it can be used like this:
let data = dataModel(json: jsonResponse)
data.settings.userName // John
data.settings.rollNumber //10
data.status //200
This is a good tool to convert the json in to data models Link
Hope it helps.

how to disable auto sorting JSON dictionary response from web service call in iOS

I am using one web service in my app. Unfortunately I am not expecting the
response to be auto sorted based on the keys. I need the original response as
it is in web. Can anyone let me know how to do this in iOS app.I am using the
following code to show the response.
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
JSON objects have unordered keys. iOS is not sorting the keys in the data structure. It's just sorting them when you print out the result (for convenience). Internal to the data structure, there is no guaranteed order. It depends on how things hash.
There is no way to use NSJSONSerialization to create an "ordered dictionary" since ordered dictionaries don't exist in JSON. The way you fix this is to use a list of dictionaries, such as:
[ { "First": "A" }, { "Second", "B" } ]
This is promised to stay in order because it's a list.
If you can't change the format, and the format relies on order, then it's not proper JSON and you'll have to parse it some other way. Typically I try to do simple string parsing (splitting on newlines for instance) to find large valid JSON "chunks" that can be handed to the parser.

Restkit mapping an array of strings

Using Restkit in my iOS project and the api is getting back a generic array of strings. How do I get access to those array of strings?
This is what is returned by the api.
{
"servers": ["http://myserver.com", "http://myotherserver.com"]
}
Assuming the response is an NSDictionary:
strings = [{response_object} objectForKey: #"servers"]
Will return an NSArray of the strings held in the servers key.
Replace {response_object} with whatever your response is. I may not be understanding your question though, it's quite vague.

How to retain order of JSON data retrieved with AFNetworking?

I am using AFNetworking to retrieve JSON data from a web service. Part of the response string I get is:
{"DATA":{"LEASE TYPE":"3 Yrs + 0 renew of 0 Yrs","LANDLORD":"","TENANT":"test comp"...
and so on. The order of the key values in the "DATA" dictionary ("LEASE TYPE","LANDLORD","TENANT"...) is important for presentation purposes. However, when AFNetworking calls NSJSONSerialization's:
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
method, the returned dictionary has the keys in a different order.
I notice that the AFJSONRequestOperation object has the server's response stored as an NSString, with everything in the correct order. However I'm not keen on parsing the JSON by hand if I can avoid it.
Can anyone suggest a way that will let me get at / keep the keys in their original order?
Thanks.
If the order is important use an array not a dictionary, dictionaries are be by their nature unordered. Or add an array of dictionary keys in the order desired.
If you have no control over the response that is sent you will have to parse the JSON yourself at least for the ordering.
When you'r creating an NSDictionary, the order will not be the same. I often recognized that dictionaries get ordered by key-name alphabetically.
But when using dictionaries the order doesn't really matter. And they shouldn't!
As the previous answers mentions dictionaries are by nature without order, but you can find here a nice class of OrderedDictionary:
http://www.cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html
http://projectswithlove.com/projects/OrderedDictionary.zip

Traverse through JSon data in dart?

After trying a lot sorry for asking such a trivial question.
Given below screenshot consist of a data that I have successfully received from the server.
I would like to know how to traverse through the data since whenever I try to cast it to something and try a foreach it gives an error.
The actual data sent from the server is a List() type.
I want to know how to cast it to same type and use it here.
I tried casting but it says unexpected token here.
Any help is appreciated.
JSON.parse return type depends on the String you try to parse. See the doc :
Parses json and build the corresponding parsed JSON value.
Parsed JSON values are of the types num, String, bool, Null, Lists of parsed JSON values or Maps from String to parsed JSON values.
From your screenshot, it seems that the return value is a List. You can do something like the following to use it (did you notice the typo in your commented code - .fore) :
final parsedList = JSON.parse(e.data)/*.fore*/;
parsedList.forEach((x){
query('#idData').appendText(x[0]);
query('#idData').appendText(x[1]);
query('#idData').appendText(x[2]);
query('#idData').appendText(x[3]);
});

Resources