I have paramaters which needed to be passed in POST type.
The paramaters are
{
"couponamt": 0,
"pincode": 110093,
"proinfo":
[
{ "prodPrice": 2289,
"prodSize": "",
"proid": 41211,
"promapid": 68804,
"proname": "Spigen SGP10905 Gunmetal iPhone 6 (5.5inch) Case ",
"qty": 1,
"vendorId": 1050
},
{ "prodPrice": 6422,
"prodSize": "3X8 Feet",
"proid": 61554,
"promapid": 110886,
"proname": "Kaka Carpet K00108 Camel Tibbati Gabbeh Carpet",
"qty": 1,
"vendorId": 1066
},
{ "prodPrice": 3996,
"prodSize": "XL",
"proid": 99003,
"promapid": 162976,
"proname": "AbsurdABWS15-625GreyWomenSweatshirt",
"qty": 4,"vendorId": 885
}
],
"shipcharge": 75,
"totalAmount": 1599,
"usedwalletamount": 0
}
I want to pass this paramter with my url to create request.And it is in the form of array.Kindly revert ASAP.
Thanks
Firstly, create NSMutableDictionary with 7 keys namely prodPrice, prodSize, proid, promapid, proname, qty, vendorId.
Set desired values for your keys.
After this, create NSMutableArray and add all your dictionaries to this array.
Now create 1 final NSMutableDictionary which will be used as value for whatever parameter key your server is expecting.
In this dictionary, set your above created NSMutableArray as value for key proinfo. Similarly set values for other keys couponamt, pincode, shipcharge etc.
Finally append this dictionary with your base url.
So as far I get the original question we need to create the below structure:
- NSMutableDictionary
-NSMutableArray
-NSDictionary
- NSDictionary
You simply need to create the NSMutableArray and NSDictionary object.
Based on your requirement you can add dictionary on respective indexes in NSMutableArray, which can be collectively added in the NSMutableDictionary.
Related
I want to show data as it came from the backend So let's have an example json file:
{
"fonts": [
{
"name": "Helvetica",
"styleIdentifier": "H0",
"size": 17
},
{
"name": "Helvetica",
"styleIdentifier": "H1",
"size": 14
},
{
"name": "Helvetica-Bold",
"styleIdentifier": "H0Bold",
"size": 17
},
{
"name": "HelveticaNeue-Light",
"styleIdentifier": "H0Light",
"size": 40
}
]
}
So i create a relationship (many - many) with ordered option selected. And by the input i see it's always write in the same way to Core Data, but when I try to fetch it
configuratation.fonts where fonts is a NSOrderedSet i get items in completly random order. I miss sth in spec? Or I should sort it somehow?
__EDIT__
Firstly when i get a data from above json I have a configuration set with empty font relation. Then I fetch this and insert it into core data with:
NSMutableArray *returnArray = [NSMutableArray new];
for(NSDictionary *fontDictionary in jsonArray) {
Font *fontObj = [Font font:fontDictionary inContext:context];
[returnArray addObject:fontObj];
}
And in this array data is in correct order. Then in configuration object i add it to NSOrderedSet by:
-(void)appendTracks:(NSArray<Font*>*)fontArray {
self.fonts = [NSOrderedSet orderedSetWithArray: fontArray];
}
And then i try to fetch it by simply use reference:
configuration.fonts
And in this step data are completly not in correct order.
Do not set the NSOrderedSet directly.
Either modify the existing set:
[self.fonts addObjectsFromArray:fontArray];
Or:
Xcode generates methods to add and remove entries from ordered sets within the generated NSManagedObject class.
Assuming you have an Entity called ManagedConfiguration which holds an ordered to many relation called fonts:
ManagedConfiguration *managedObjectConfigurationInstance = //create or fetch configuration in ManagedObjectContext
NSOrderedSet<ManagedFont> *fonts = //created or fetched fonts in wanted order
managedObjectConfigurationInstance.addToFonts(fonts)
replaceFonts, removeFromFontsAtIndex aso. methods are also generated.
Depending on your requirements, you might want to store the fonts in random order and apply a NSSortDescriptor to your NSFetchRequest to fetch the data in a specific order.
Instead of trying to set the data directly to your property(fonts), you need to first fetch the mutable copy of your NSOrderedSet from the NSmanagedObject Subclass (I assume it to be Font).
NSMutableOrderedSet *orderedSet = [self mutableOrderedSetValueForKey:#"fonts"];
Then add the objects from the array to this orderedSet.
[orderedSet addObjectsFromArray:array];
Now you would have properly set the the values for the key fonts.
So your appendTracks function would now look like this.
-(void)appendTracks:(NSArray<Font*>*)fontArray {
NSMutableOrderedSet *orderedSet = [self mutableOrderedSetValueForKey:#"fonts"];
[orderedSet addObjectsFromArray:fontArray];
}
Now execute your fetch request. You should receive the data in the set order in the array.
PS:I had used your JSON response to test this.
not really sure how to even word this question BUT I have some JSON that I need to parse which is formatted like so:-
"nodes": {
"4": {
"node_id": 4,
"title": "TITLE 1",
"description": "",
},
"7": {
"node_id": 7,
"title": "TITLE 2",
"description": "",
},
"12": {
"node_id": 12,
"title": "TITLE 3",
"description": "",
},
Normally I would grab values with the standard [dictionary objectForKey#"key"] but as the items begin with an integer (string) I am finding it hard to parse correctly. Am I missing something really simple here?
If you just want to access one value than you would do the following.
// Assume JSONObject is the "root" dictionary
NSDictionary *fourDictionary = JSONObject[#"nodes"]["4"] // This will get the object from "4":{}
Now if the JSON in question can have a dynamic number of objects than this is much trickier. The easiest solution would be to get the provider of the JSON to rewrite it as an array of objects. You could than look up the object you want using the object's node_id value.
If this is not possible than you could attempt to write a for loop to loop through all of the keys in the "nodes" object and access the items from the dictionary that way.
i.e.
NSMutableArray *arrayOfNodes = [NSMutableArray array];
NSDictionary *nodes = JSONObject[#"nodes"];
for(NSString *numberKey in [nodes allKeys])
{
NSDictionary *nodeObject = nodes[numberKey]
[arrayOfNodes addObject:nodeObject];
}
// Do anything else with the nodes now that they are in an array.
I have a json which contain objects where each object have child object, for example
[
{
"id": 1,
"name": "obj1"
},
{
"id": 2,
"name": "obj2"
},
{
"id": 3,
"name": "obj3",
"child": {
"id": 2,
"name": "obj2"
}
},
{
"id": 4,
"name": "obj4",
"child": {
"id": 5,
"name": "obj5"
}
}
]
So in core data i have entity MyObject which has relation to child (to itself, to one), and relation to parent (to many)
So when i try fetch object by predicate like
[NSPredicate predicateWithFormat:#"parent.#count = 0"]
I got only object with id in [1,3,4], but no with id = 2 (here error) and id = 5 (here all correct), because it's was sets parent when it's mapped when object with id = 3 save to data base.
If no use predicate i got 5 object, include obj5.
But i need fetch from coredata exactly count of object what i got from json.
I need fetch only object with id in [1,2,3,4].
How do i need write predicate, if it's possible?
The data you got from JSON is a subset of all your objects, but the logic according to which it is selected is not persisted in your object model.
You persist the relationship between child and parent (hint: for readability, rename it as parents if it is to-many), but the selection in your JSON example is not based on any of those criteria.
One easy way to get all the objects is to extract the top level ids delivered by the JSON feed and use that in the predicate:
NSArray *ids = [jsonArray valueForKey:#"id"];
[NSPredicate predicateWithFormat:#"idNumber in %#", ids];
(Note that I changed your attribute name from id to idNumber in order to avoid possible language quirks, as id is a reserved word.)
I am getting some data from WebService (which is a json data)
Exact input sent by Webservice is:
[
{
"id": "C-62",
"title": "testing testing",
"type": "image",
"thumb": "",
"LinkId": "ABC",
"fileSize":1074,
"level":0,
},
{
"id": "C-63",
"title": "testing ab testing",
"type": "audio",
"thumb": "",
"LinkId": "ABCD",
"fileSize":1074,
"level":1,
}
]
As I can see in input data that only fileSize is a integer type Key-Value pair
remaining all are in string format.
When I convert that NSData onto NSArray using following code
NSArray *dataArray = nil;
dataArray = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
I get "dataArray" like this
{
"id": "C-62",
"title": "testing testing",
"type": image,
"thumb": "",
"LinkId": "ABC",
"fileSize":1074,
"level":0,
},
{
"id": "C-63",
"title": "testing ab testing",
"type": audio,
"thumb": "",
"LinkId": "ABCD",
"fileSize":1074,
"level":1,
}
The "type" Key-Value pair changes to "int" .All other key-value pairs are in same state.
Please help me in order to convert the input data into the same format as sent by web service.
I am using iOS 7.
You just got yourself confused. You confuse NSLog output with what is really stored. You are also not saying the truth when you claim that only the "fileSize" field contains numbers, because clearly the "level" field does as well.
NSLog only shows strings with quotes when necessary. A string "10" would be displayed as 10 without the quotes. You can really rely on NSJSONSerializer not doing anything behind your back.
NSJSONSerialization will convert scalar numbers to NSNumbers. That's the only way these can participate in collections (arrays and dictionaries). To convert to int, access the NSNumber and convert it as follows...
NSArray *dataArray = // the de-serialized json
NSDictionary *dictionary = dataArray[0]; // the first dictionary
NSNumber *number = dictionary[#"fileSize"];
// turn an NSNumber representing an integer to a plain int
int fileSizeInt = [number intValue];
But don't try to reinsert that int back into the dictionary.
The one tricky thing about JSON on iOS is figuring out the data type of an arbitrary NSNumber. I chronicled my difficulties in this question.
A large number might be floating-point or integer, and if you attempt to extract one when you really have the other you lose significant digits. And, obviously (in retrospect), if you extract a too-large value into an int you will lose high-order bits and get totally wrong values.
(This isn't quite so difficult if you know in advance that certain values are of certain types. Then it's just a matter of using the proper "verb" to extract the expected type of value.)
I thought this question would work for my situation, but my lack of experience with Mantle and iOS in general has dead ended my train of thought. Basically, I have a big chunk of JSON with nested dictionaries and arrays that I want to convert into Mantle objects.
"features": {
"App": {
"status": "_ACTIVE",
"unavailableReasons": [],
"modernCapabilities": [{
"capabilityType": "LOCK_AUTO_REPLY",
"providerStatuses": [{
"providerType": "MY_PROVIDER",
"status": false,
"unavailableReasons": ["NOT_SUPPORTED_BY_PRODUCT", "DEVICE_OS_NOT_SUPPORTED"]
}]
},
...
...
{
"capabilityType": "LOCK_CONTACT_WHITELIST",
"providerStatuses": [{
"providerType": "OTHER_PROVIDER",
"status": true,
"unavailableReasons": []
}]
}
]}
}
I want to be able to implement a similar solution to that linked above, namely iterating down the dictionary for the "Features" key, and applying a transform to each key/value pair. So, in this case, to the "App" key and it's dictionary value (and later, the "modernCapabilities" key and it's array, etc. etc.) I know that for the later steps I'll need separate model classes, and those exist, but I'm having trouble with the first step, the transform on the "App" key and it's value.
Here's what I have right now:
+ (NSValueTransformer *)featureTypesJSONTransformer {
NSValueTransformer *transformer = [NSValueTransformer valueTransformerForName:#"FeatureStatus"];
return [MTLValueTransformer transformerWithBlock:^NSDictionary *(NSDictionary *features) {
NSMutableDictionary *transformedValues = [[NSMutableDictionary alloc] init];
for (NSString *key in features) {
id transformedValue = [transformer transformedValue:[features objectForKey:key]];
if (transformedValue ) {
[transformedValues setObject:transformedValue forKey:key];
}
}
return transformedValues;
}];
}
As you can see from the code, I'm trying to preserve the key, and attach it to a new Dictionary with the value being another transform, FeatureStatus in this case (#{ "App" : })
The problem is that there is no [FeatureStatus transformedValue:], although I do have a JSONKeyPathsForPropetyKey since I want to map the 'status', 'unavailableReasons' and 'modernCapabilities' keys later on.
What's my next step? How can I register a ValueTransform that does what I want it to do?