Convert JSON Anyobject to Int64

Convert JSON AnyObject to Int64

JSON numbers are NSNumber, so you'll want to go through there.

import Foundation
var json:AnyObject = NSNumber(longLong: 1234567890123456789)

var num = json as? NSNumber
var result = num?.longLongValue

Note that result is Int64?, since you don't know that this conversion will be successful.

Swift: Cast Any Object to Int64 = nil

In

let dict : [String : AnyObject] = ["intValue": 1234, "stringValue" : "some text"]

the number 1234 is stored as an NSNumber object, and that can
be cast to Int, UInt, Float, ..., but not to the fixed
size integer types like Int64.

To retrieve a 64-bit value even on 32-bit platforms, you have to
go via NSNumber explicitly:

if let val = dict["intValue"] as? NSNumber {
let int64value = val.longLongValue // This is an `Int64`
print(int64value)
}

How to parse Int with a value more than 2147483647 from JSON in Swift

Int can be a 32-bit or 64-bit integer, depending on the platform.
As already said in the comments, you need Int64 or UInt64 to store
a value > 2147483647 on all platforms.

You cannot cast from AnyObject to Int64 directly, therefore
the conversion is via NSNumber:

guard let userId = (dict["id"] as? NSNumber)?.longLongValue  else { return }

For Swift 3, replace longLongValue by int64Value.

swift: convert long/int64 to date

Just let JSONDecoder do the job by using the appropriate date decoding strategy

let json = """
{"id" : 1, "date" : 1529704800000}
"""

struct Example : Decodable {
let id : Int
let date : Date
}

let data = Data(json.utf8)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .millisecondsSince1970
do {
let result = try decoder.decode(Example.self, from: data)
print(result) // Example(id: 1, date: 2018-06-22 22:00:00 +0000)
} catch {
print(error)
}

Note: Don't make an asynchronous task synchronous. Learn to understand asynchronous data processing and use a completion handler.

How do I turn a C# object into a JSON string in .NET?

Please Note

Microsoft recommends that you DO NOT USE JavaScriptSerializer

See the header of the documentation page:

For .NET Framework 4.7.2 and later versions, use the APIs in the System.Text.Json namespace for serialization and deserialization. For earlier versions of .NET Framework, use Newtonsoft.Json.



Original answer:

You could use the JavaScriptSerializer class (add reference to System.Web.Extensions):

using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);

A full example:

using System;
using System.Web.Script.Serialization;

public class MyDate
{
public int year;
public int month;
public int day;
}

public class Lad
{
public string firstName;
public string lastName;
public MyDate dateOfBirth;
}

class Program
{
static void Main()
{
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = new JavaScriptSerializer().Serialize(obj);
Console.WriteLine(json);
}
}

Swift AnyObject is not convertible to String/Int

In Swift, String and Int are not objects. This is why you are getting the error message. You need to cast to NSString and NSNumber which are objects. Once you have these, they are assignable to variables of the type String and Int.

I recommend the following syntax:

if let id = reminderJSON["id"] as? NSNumber {
// If we get here, we know "id" exists in the dictionary, and we know that we
// got the type right.
self.id = id
}

if let receiver = reminderJSON["send_reminder_to"] as? NSString {
// If we get here, we know "send_reminder_to" exists in the dictionary, and we
// know we got the type right.
self.receiver = receiver
}

Cannot convert value of type '(key: String, value: AnyObject)' to expected argument type '[String : AnyObject]'

  • First of all classes are supposed to be named in singular form Post / ThumbImage. The datasource array e.g. posts contains Post instances and each Post instance contains an array thumbnailImages of ThumbImage instances. These semantics make it easier to understand the design.
  • Second of all JSON dictionaries in Swift 3+ are [String:Any]
  • Third of all according to the initialization rules the super call must be performed after initializing all stored properties.

The value of key thumbnail_images is a dictionary containing dictionaries. The error occurs because you are using the array enumeration syntax which treats the dictionary as an array of tuples.

The dictionary can be parsed to use the key as size name and the value to pass the parameters.

I have no idea why you are using NSObject subclasses but I'm sure you have your reasons.


This is the Thumbnail class

class ThumbImage: NSObject {

let size: String
var url : URL?
let width : Int
let height : Int

init(size : String, parameters: [String: Any]) {

self.size = size
if let urlString = parameters["url"] as? String {
self.url = URL(string: urlString)
}
self.width = parameters["width"] as? Int ?? 0
self.height = parameters["height"] as? Int ?? 0
super.init()
}
}

and this the Post class

class Post: NSObject {

var title: String
var excerpt: String
var content: String
var thumbnailImages = [ThumbImage]()

init(dict: [String: Any])
{
self.title = dict["title"] as? String ?? ""
self.excerpt = dict["excerpt"] as? String ?? ""
self.content = dict["content"] as? String ?? ""
super.init()
if let images = dict["thumbnail_images"] as? [String: [String:Any] ] {
for (key, value) in images {
thumbnailImages.append(ThumbImage(size: key, parameters: value))
}
}
}
}

How to convert Any to Int in Swift

var i = users[0]["Age"] as Int

As GoZoner points out, if you don't know that the downcast will succeed, use:

var i = users[0]["Age"] as? Int

The result will be nil if it fails



Related Topics



Leave a reply



Submit