How to cast a JSON DateTime to actionscript3? - actionscript-3

My json.start returns 2012-12-21 10:02:35
I try var start:Date = json.start as Date; and get a null.

There are several ways to do this:
use a DateFormatter object: DateFormatter
use a regular expression and build a Date object: RegEx

var start:Date = DateFormatter.parseDateString('2012-12-21 10:02:35');

Related

How to parse JSON with dynamic field names with Gson in Kotlin?

I have looked at a lot of articles but can't seem to figure out the answer. The problem being is that I get a json file like this from my api:
{
"forecast": {
"2020-01-04": {
"date": "2020-01-04",
"mintemp": 7,
"maxtemp": 11,
"avgtemp": 9,
"hourly":
...
}
}
}
The problem is that the "key" in this JSON is always the day of today (2020-01-04). The way I do this now is like this:
data class ForecastDaysContainer(
#SerializedName("2020-01-04")
var forecastday1: FutureWeatherEntry,
#SerializedName("2020-01-05")
val forecastday2: FutureWeatherEntry,
#SerializedName("2020-01-06")
val forecastday3: FutureWeatherEntry,
#SerializedName("2020-01-07")
val forecastday4: FutureWeatherEntry,
#SerializedName("2020-01-08")
val forecastday5: FutureWeatherEntry,
#SerializedName("2020-01-09")
val forecastday6: FutureWeatherEntry,
#SerializedName("2020-01-10")
val forecastday7: FutureWeatherEntry
)
This of course results in me changing the dates every day manually.
Is there any way I can set the #SerializedName to the date of today? When I try this with:
LocalDate.now().toString()
I get the error:
An annotation argument must be a compile-time constant
I can't seem to find a decent fix for this in Kotlin.
It is not possible to have annotation data to be created dynamically. So you need to think it the other way around. With Gson you could try to implement custom JsonDeserializer that parses fields dynamically by that date value.
However I think that most convenient way would be to use Map as comment suggests. If you can make your ForecastDaysContainer like this:
data class ForecastDaysContainer(
var forecast : Map<String, FutureWeatherEntry>
)
When deserialized you will then have a Map that contains possibly many days with the date as the key. So like:
val container = gson.fromJson(json, ForecastDaysContainer::class.java);
val forecast = container.forecast.get("2020-01-04");
Gson has parse() method for that.
val key = "2020-01-04" // This is generated, probably?
val json = JsonParser().parse(jsonString)
val result = json.asJsonObject["forecast"].asJsonObject[key]

Date Format in Json request/response of an API

I am having a Date field - startDate in my pojo.
In API request body in JSON I have to mention date in following format -
{
...
"startDate" : "2017-05-19T14:00:00",
...
}
But in the response I get the following format -
{
...
"startDate" : "2017-05-19 14:00:00",
...
}
There is no 'T' in the response JSON.
What should I do to make it consistent and have the 'T' in response as well.
You can use below code for yyyy-MM-dd'T'HH:mm:ss to yyyy-MM-dd HH:mm:ss at the time of request.
String time = "2017-05-19T14:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);
System.out.println(formattedTime);
OR
you can use below code for yyyy-MM-dd HH:mm:ss to yyyy-MM-dd'T'HH:mm:ss at the time of response.
String time = "2017-05-19 14:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);
System.out.println(formattedTime);
There two ways to achieve the result.
Use String in server side.So you can get the same result in both
request and response.
You could convert date object into Long(millisecond).
For your information, The T is just a literal to separate the date from the time.
You can use the below code
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")

Realm format date JSON swift

I had JSON with a date "date_use" :
{"expense":
{"id":1,
"amount":123.3,
"date_use":"2015-07-04T00:00:00Z"}
}
I had an error on date format when I execute this code :
self.realm!.create(Expense.self, value:json["expense"].object, update: true)
Error :
Terminating app due to uncaught exception 'RLMException', reason:
'Invalid value '2015-07-04T00:00:00Z' for property 'date_use'
My question is : What is the good date format for Realm?
The problem here is not the particular date format, but that JSON doesn't support a native date type at all. So you have to serialize dates to a string format. Using RFC 3339, like you have to deal with, is generally a good choice because it avoids ambiguities, so you can stick with that.
Realm's create method doesn't expect deserialized JSON, but a dictionary representation of your object. This expects that you have done already the preprocessing step of transforming date string representations back to Cocoa's native type NSDate. This isn't done automatically because there are date formats, which are ambiguous (unlike yours), which e.g do not provide information about the timezone.
Good news is there are excellent third-party libraries e.g. Realm-JSON, which make it a whole lot easier to deal with that. It brings built-in support for that.
This would also allow to map the property naming scheme returned by your API, e.g. date_use to names which conforms to the more broadly used camel-case dateUse.
If you don't want to introduce another dependency just for that use case, you can use and configure NSDateFormatter to parse dates conforming to your particular subset of the RFC 3339 standard, assuming they always use UTC as timezone, marked through the Z suffix.
// Setup the RFC 3339 date formatter
let rfc3339DateFormatter = NSDateFormatter()
let enUSPOSIXLocale = NSLocale(localeIdentifier: "en_US_POSIX")
rfc3339DateFormatter.locale = enUSPOSIXLocale
rfc3339DateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
rfc3339DateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
// Convert the RFC 3339 date time string to an NSDate
var json: AnyObject! = nil
var value = json["expense"] as! [String : AnyObject]
let date: NSDate?
if let dateString = value["date_use"] as? String {
date = rfc3339DateFormatter.dateFromString(dateString)
} else {
date = nil
}
value["date_use"] = date
// Create your object
self.realm!.create(Expense.self, value: value, update: true)

deserialize json to general object (without predefined schema)

I'm trying to use json.net.
I'd like to get a string (in json format) and convert it to general json object, without predefined schema.
somelting like
var jsonString = #"{\""id\"": 1,\""name\"": \""A green door\""}";
var jsonMessage = JsonConvert.DeserializeObject<JObject>(jsonString);
var myValue = jsonMessage["name"]
Is that something doable? didn't make it work
Your string is malformed, try this string instead:
var jsonString = "{\"id\": 1,\"name\": \"A green door\"}";
You could also shorten this a little bit:
string name = JObject.Parse(jsonString)["name"].ToObject<string>();

Error while using Newtonsoft.Json to parse a Json string

My JSON string looks like this. Please note that it has escape characters.
string json = "\"{\\\"Status\\\":true,\\\"ID\\\":24501}\"";
When I use the Parse method like below I run into an error stated below:
JObject o = JObject.Parse(json);
Error reading JObject from JsonReader. Current JsonReader item is not an object: String
How do I get rid of this error or is there any other method to parse my json string and fetch the values?
Remove first and last quotes:
string json = "{\"Status\":true,\"ID\":24501}";
See the Json format here.
It seems like your object is double encoded. Try:
string json = "{\"Status\":true,\"ID\":24501}";
You need something like this
json = json.Replace(#"\", string.Empty).Trim(new char[]{'\"'})
in here format should be something like this:
string jsonNew = #"{'Status': True,'ID': 24501 }";
As SolarBear says in his comment, the problem is double-escaping.
To get the proper format, like this:
string json = "{\"Status\":true,\"ID\":24501}";
Do something like this:
json = json.Replace("\\\\", "\\");
Had similar issue today. My solution to this is contained in this extension method (using c#):
public static class StringExtensions
{
public static string RemoveDoubleEncoding(this string text)
{
if(string.IsNullOrEmpty(text))
return string.Empty;
var result = text.TrimStart('\"').TrimEnd('\"');
result = result.Replace(#"\", string.Empty);
return result;
}
}