How can I insert my array of Objects in a JSON? - json

I've created an Array of Objects in Swift which has the following structure:
var myCart:[FoodItem] = []
var dump:
▿ 3 elements
▿ [0]: TablePinAdolfoTesting.FoodItem #0
- id: 5
- name: Taco
- cant: 2
▿ [1]: TablePinAdolfoTesting.FoodItem #1
- id: 6
- name: Burrito
- cant: 1
▿ [2]: TablePinAdolfoTesting.FoodItem #2
- id: 4
- name: Enchiladas
- cant: 3
I used Alamofire to get said object from my API but now, after changing them a little bit, I want to insert it into a new JSON which I created like so:
var json: JSON = ["idUser": idUser, "total_loyalty_points": totalLP, "total_price": totalPrice, "car": []]
printed json:
{
"total_price" : 50000,
"car" : [
],
"idUser" : 58,
"total_loyalty_points" : 5000
}
I have 2 issues with this...
for some reason "car" is being placed at the 2nd position even though I put it last during the JSON declaration.
The second issue is that I don't know how to place my Array of Objects within that JSON to obtain something like this:
{"idUser": (int),
"total_loyalty_points": (double),
"total_price":(double),
"car":[
{
"id": (string),
"name": (string),
"cant": (int)
}
]
}
Where "car" is an Array of Objects within that JSON. I would prefer to do this using SwiftyJSON if possible to maintain consistency but it is not a requirement.
One thing that I tried but does not work is the following
for object in cart.myCart{
var name = [String: String]()
name["id"] = object.id
name["name"] = object.name
json["car"] = JSON(name)
json["car"]["cant"] = JSON(object.cant)
}
The reason it does not work is that this will not create an array in Cart, it will just overwrite the JSON
Thanks.

For first problem there is no solution as Map or Dictionary doesn't maintain the order.
Second problem is because of you are assigning json["car"] to JSON which is a object not array of objects. Modified code is:
var cars = [[String: String]]()
for object in cart.myCart{
var name = [String: String]()
name["id"] = object.id
name["name"] = object.name
name["cant"] = object.cant
cars.append(name)
}
json["car"] = JSON(cars)

Related

How to loop and get the json object

{
"result": [
{
"id": "a258377906705d889422fd0b41c324b8",
"coordinate": {
"London": {
"x": 65.565709,
"y": 98.931235
},
"New_York": {
"x": 37.59751,
"y": 47.448718
}
}
}
]
}
If I have a json like the above one,
how can I loop to get the x,y coordinate and if i get more data to get, how can I get it?
If I want to also get the London and New York to add to an array list, how can I do it (cannot directly add the name because there are more than two data)?
You can parse it and then use it using JSON.parse( insert json here ).
Basically what it does is that it takes your JSON string and converts it into a usable JSON.
For adding new objects into another object, I recommend using Object.assign().
You can refer the details here: Link
Here is an example given from the site:
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
Object.assign() takes a target object as the first parameter and modifies it with the additional parameters that we're provided.
In your case, you can update your object like this:
var countryCoord = JSON.parse(yourjsondata); // parse the json that you included
Object.assign(countryCoord, newCoord, newCoord2,...etc); //this would update countryCoord alone
Online parser: Link
You have to handle the json and understand where you are getting the JSONObject and where you are getting the JSONArray, On basis of that you can parse the JSON accordingly.
Please refer the link for more information on parsing json object with nested items in Java:
Retrieving nested arrays values with java

Nested Arrays throwing error in realm.create(value: JSON) for Swift

I'm using Realm in my Swift project and have a rather long JSON file with a couple of nested properties. I'm aware that in order for Realm to use this serialized JSON data directly, the properties need to match exactly (https://realm.io/docs/swift/latest/#json).
But because Realm Lists need to have an Object instead of a String, I have to use something like List with Requirement being a Realm Object that holds a single String called 'value'.
When I run this code:
try! realm.write {
let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
let exhibit = Exhibit(value: json)
exhibit.id = "1"
realm.add(exhibit, update: true)
}
I get this error message:
*** Terminating app due to uncaught exception 'RLMException', reason: 'req1' to initialize object of type 'Requirements': missing key 'value''
Here's a shortened version of the JSON I'm feeding in there:
{
"exhibit_name": "test1",
"requirements": [
"req1",
"req2"
],
"geofence": {
"latitude": 36.40599779999999,
"longitude": -105.57696279999999,
"radius": 500
}
}
And my Realm model classes are this:
class Exhibit: Object {
override static func primaryKey() -> String? {
return "id"
}
dynamic var id = "0" //primary key
dynamic var exhibit_name: String = ""
let requirements = List<Requirements>()
dynamic var geofence: Geofence?
}
class Geofence: Object {
dynamic var latitude: Float = 0.0
dynamic var longitude: Float = 0.0
dynamic var radius: Float = 0.0
}
class Requirements: Object {
dynamic var value = ""
}
I find it interesting that I'm not getting any errors for the Geofence property, since that's a dictionary.
How do I set up the Requirements model to make this work properly?
Unfortunately you can't just setup your Requirements model in a different way, which would allow you to directly map your JSON to Realm objects.
The init(value: AnyObject) initializer expects either a dictionary, where the keys are the names of your object properties, or an array, where the property values are ordered in the same like they are defined in your object model. This initializer is recursively called for related objects.
So to make that work, you will need to transform your JSON, so that you nest the string values into either dictionaries or arrays. In your specific case you could achieve that like seen below:
…
var jsonDict = json as! [String : AnyObject]
jsonDict["requirements"] = jsonDict["requirements"].map { ["value": $0] }
let exhibit = Exhibit(value: jsonDict)
…
Side Note
I'd recommend using singular names for your Realm model object classes (here Requirement instead Requirements) as each object just represent a single entity, even if you use them only in to-many relationships.

Updating values within array of dictionaries using Swift

I am teaching myself Swift these days and have trouble understanding how to update values in dictionaries stored in an array. The array consists of dictionaries read from file using JSON (I am using SwiftyJSON). The JSON file looks like this:
{
"test2" : [
{
"files" : "203",
"url" : "Optional(\"\/Users\/heisan\/test\/\")",
"date" : "April 6, 2015 at 15:23:40 EDT"
}
]
}
Each key:value pair in the dictionaries consists of String:Array where the Array again consists of String:String dictionaries. My function for updating the content for specific key looks like this:
#objc func addOptionForKey(key: String, date: NSDate, url: NSURL, files: NSNumber)-> Bool {
let dictData: NSData? = self.createDataOfDictionary()
if (dictData != nil) {
let json = JSON(data: dictData!)
for (localkey: String, var subJson: JSON) in json {
var backups: Array = [Dictionary<String,AnyObject>]()
var restores = subJson.arrayValue
for restore in restores {
let innerDict: [String:String] = ["url":restore["url"].stringValue,
"files":restore["files"].stringValue,
"date":restore["date"].stringValue]
backups.append(innerDict)
}
self.restoreDict[localkey]=backups
}
return true
}
Here, a the restoreDict property is defined as
self.restoreDict = String:[AnyObject]
The function crashes when I try to update my array for the specific key:
self.restoreDict[localkey]=backups
I am sure I am doing some amateur error here but a kick in the right direction would be greatly appreciated. Thanks. T
Update: My problem turned out to be related to my version of Xcode and Swift. When I switched to Xcode 6.3 + Swift 1.2 as well as moving away from using swiftJSON (as Swift 1.2 has many improvements for handling JSON) everything works as expected.
var restoreDict = [String:[String:AnyObject]]()
let test2 = ["files" : 203, "url" : "blah", "date" : "April 6, 2015 at 15:23:40 EDT"]
restoreDict["local"] = test2
println(restoreDict)
// prints "[local: [files: 203, url: blah, date: April 6, 2015 at 15:23:40 EDT]]"

Is it possible? xAxis categories with Json?

Highcharts;
I'm trying to change categories dynamically in a column chart with a json. Something like this...
[{y:1,"other":"other","category":"namecategory"}....]
..
xAxis: {
categories: this.category,
maxZoom: 1
},
Is it possible?
Thanks. :D
You can dynamically load your categoreis i.e by json or other and then use setCategories which allows to change categoreis, dynamically.
Ok, maybe you can try it something like this:
var jsonData = [{
"y": "1",
"other": "other",
"category": "namecategory1"
}, {
"y": "2",
"other": "another",
"category": "namecategory2"
}];
// var jsObject = JSON.parse(jsonData);
var categories = new Array();
for (var p in jsonData) {
categories.push(jsonData[p].category);
}
chart.xAxis[0].setCategories(categories);
I think you need to set categories as an Array of primitive js types such as number or string.
Example:
categories: ['Apples', 'Bananas', 'Oranges']
As it is mentioned here: http://api.highcharts.com/highcharts#xAxis.categories :
"If categories are present for the xAxis, names are used instead of numbers for that axis."
Maybe, when you mention JSON are you talking about Object Literals? (because "y" key in your sample is not quoted.)
In fact , you CAN use an Array of Object Literals. But they will be displayed as "[Object]" in the xAxis.
An object literal is a pair of curly braces surrounding zero or more name/value
pairs. An object literal can appear anywhere an expression can appear:
var empty_object = {};
var stooge = {
first_name: "Jerome",
last_name: "Howard"
};
The quotes around a property’s name in an object literal are optional if the name would be a legal
JavaScript name and not a reserved word.
Maybe you can pre-process your JSON data an build an Array to be used in categories.

Deserialize JSON using JSON.net in Wp7 application

I have this JSON format:
string jsonFormat = #"{
""Applications"": {
""data"": {
""Application named one"": [
{
""index"" : ""1"",
""name"" : ""One"",
""active"" : ""1"",
""excluded"" : ""false""
}
],
""Application named two"": [
{
""index"" : ""2"",
""forum"" : ""yes"",
}
]
}
}
}";
How exactly I can acces data childrens ? I need to retreive Application named one and Application named two - for each also the attributes with their values - the attributes are different from Application to Application.
Untill now I have:
JObject resultt= JObject.Parse(jsonFormat);
// get JSON result objects into a list
IList<JToken> results = resultt["Applications"]["data"].Children().ToList();
I looked over JSON.net documentation and could not find a solution for this...
Any help will be very usefull. Thank you.
I think you are looking for something like this:
JObject jObject = JObject.Parse(jsonFormat);
int index = jObject
.Value<JObject>("Applications")
.Value<JObject>("data")
.Value<JArray>("Application named one")
.First
.Value<int>("index");
Basically the idea is to use the Value method with the type you are expecting to retrieve a specific json element (JObject, JArray, ...) or parse a .NET value (int, string, bool, ...).