Date format in TJSONObject - json

I am converting a TFDMemTable to JSON via SaveToStream(). Then I use TJSONObject::ParseJSONValue() to get the JSON object. After some parsing, I return the JSON in string format via ToString().
TStringStream *Stream = new TStringStream();
TJSONObject *Json = new TJSONObject();
fdMemTable->SaveToStream(Stream.get(), sfJSON);
TJSONObject *JsonParsed = (TJSONObject*) Json->ParseJSONValue(Stream->DataString);
...
return JsonParsed->ToString();
All through this, the dates remain in the form 20180329T013152 instead of 2018-03-29T01:31:52. I am looking to see if there is any option that I can set. TJsonOptions seems to be close to what I am looking for, but seems to only be used with ObjectToJsonString().
Does anyone know any such option, or do I have to do this conversion per date/time field?

There is no date/time type in JSON. Date/time values are just arbitrary string values with formatting. So, unless TFDMemTable provides an option to specify date/time formatting for its JSON output, then you will have to handle this on a per-field basis.
BTW, you don't need to create a TJSONObject object to call ParseJSONValue():
TJSONObject *JsonParsed = (TJSONObject*) TJSONObject::ParseJSONValue(Stream->DataString);

Related

how can I convert an object of type Any to a specific class type?

I am using Kotlin and I have a service that is getting an object of type Any (this cannot be changed)
The problem with Any is that is an object of 20+ fields and I just need one of them to use it as a filter... therefore I cannot do a simple cast.
So, my object is like: (when I print it)
{messageId=123, userId=32323, address=Some city, phone=111605,type=TYPE1.....
I want to convert it using Kotlinx or Jackson but I cannot convert it first to the expected String format, doing a parseFromString(myObject) will result in an exception as well of a wrong Json format.
I want to convert it to a class like this
#Serializable
private data class UserType(val type: String)
type is the only field I care about.
My convertion is via kotlinx
val format = Json { ignoreUnknownKeys = true }
format.decodeFromString<UserType>(myObject)
I even tried this to see if I can make it in the proper Json format
format.encodeToString(original)
Any idea what I could do here that would be a lightweight solution?
This is my Any type https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/

Calling an API returns expected JSONArray, found JSONObject

I'm calling an API from Go and trying to push json string data from another api call into it.
I can hand craft the calls using a payload like
payload := strings.NewReader('[{"value1":333, "value2":444}]'
and everything is happy.
I'm now trying to covert this to take the json string {"value1":333, "value2":444} as an input parameter of type string to a function, but when I try and use that as the payload, the api is responding with
expected type: JSONArray, found: JSONObject
I naively tried setting the input to the function as []string and appending the data to an array as the input, but then strings.NewReader complained that it was being fed an array.. which is was.
I'm at a loss to work out how to convert a string of json into a json array that the api will be happy with.
I tried just surrounding the string with [] but the compiler threw a fit about incorrect line termination.
Must have been doing something wrong with the string, surrounding the {} with [] let the function pass the data, but there must be a better way than this.
Any ideas, or am I making this harder than it should be?
You were on the right track with the brackets, but you actually need to append the characters to the string. For example:
str := `{"value1":333, "value2":444}`
str = "[" + str + "]"
// [{"value1":333, "value2":444}]
https://play.golang.org/p/rWHCLDCAngd
If you use brackets outside a string or rune literal, then it is parsed as Go language syntax.

Are Json values type specific

I'm trying to understand what is going on when I query data from a database and provide it to JSON and then push it to a GUI, in regards to what and when is converting to a string.
If I make a call to a database and provide this data as JSON to the front end, my JSON may look like
MyData{ [["Name": "Anna", "Age": 50],["Name": "Bob", "Age": 40 ]};
Visually it appears as if the value for Name is a string (as it's in quote marks) and the value for Age is an integer (as of no quote marks).
My 2 questions are
Is my understanding that the value for Name is a string and the value of Age is an integer or does JavaScript convert/cast behind the scenes?
How would I specify the type DateTime. According to The "right" JSON date format I actually just ensure the format is correct but ultimately it's a string.
Is my understanding that the value for Name is a string and the value of Age is an integer...?
Almost. It's a number, which may or may not be an integer. For instance, 10.5 is a number, but not an integer.
...or does JavaScript convert/cast behind the scenes?
JavaScript and JSON are different things. JSON defines that the number will be represented by a specific format of digits, . and possibly the e or E character. Whatever environment you're parsing the JSON in will map that number to an appropriate data type in its environment. In JavaScript's case, it's an IEEE-754 double-precision binary floating point number. So in that sense, JavaScript may cast/convert the number, if the JSON defines a number that can't be accurately represented in IEEE-754, such as 9007199254740999 (which becomes the number 9007199254741000 because IEEE-754 only has ~15 digits of decimal precision).
How would I specify the type DateTime. According to The "right" JSON date format I actually just ensure the format is correct but ultimately it's a string.
JSON has a fixed number of types: object, array, string, number, boolean, null. You can't add your own. So what you do is encode any type meta-data you want into either the key or value, or use an object with separate properties for type and value, and enforce that agreement at both ends.
An example of doing this is the common format for encoding date/time values: "/Date(1465198261547)/". As far as the JSON parser is concerned, that's just a string, but many projects use it as an indicator that it's actually a date, with the number in the parens being the number of milliseconds since The Epoch (Jan 1 1970 at midnight, GMT).
Two concepts related to this are a replacer and a reviver: When converting a native structure to JSON, the JSON serializer you're using may support a replacer which lets you replace a value during the serialization with another value. The JSON parser you're using may support a reviver that lets you handle the process in the other direction.
For example, if you were writing JavaScript code and wanted to preserve Dates across a JSON layer, you might do this when serializing to JSON:
var obj = {
foo: "bar",
answer: 42,
date: new Date()
};
var json = JSON.stringify(obj, function(key, value) {
var rawValue = this[key];
if (rawValue instanceof Date) {
// It's a date, convert it to our special format
return "/Date(" + rawValue.getTime() + ")/";
}
return value;
});
console.log(json);
That uses the "replacer" parameter of JSON.stringify to encode dates in the way I described earlier.
Then you might do this when parsing that JSON:
var json = '{"foo":"bar","answer":42,"date":"/Date(1465199095286)/"}';
var rexIsDate = /^\/Date\((-?\d+)\)\/$/;
var obj = JSON.parse(json, function(key, value) {
var match;
if (typeof value == "string" && (match = rexIsDate.exec(value)) != null) {
// It's a date, create a Date instance using the number
return new Date(+match[1]);
}
return value;
});
console.log(obj);
That uses a "reviver" to detect keys in the special format and convert them back into Date instances.
The specific format of a JSON string can be described by JSON Schema, as described here; in particular, date-time apparently is a type already defined in JSON Schema.

ExtJS: which values does the Ext.picker.Date accept?

I have a datepicker in my form and it gets the value from the form.load in JSON format.
Which values does the datepicker support?
Because it won't bind this value:\/Date(1241215200000)\/.
I already have a convert function for the JSON format but I can't configure the field with a convert or renderer config.
convertDate = function (value) {
if (value == null) return null;
return new Date(parseInt(value.replace("/Date(", ""), 10));
};
The value have to be a valid JavaScript date or Ext.Date. So you should bind it like
new Date(1241215200000)
For example the Newtonsoft JSON serializer is capable of returning this for a given date. But if all fails you may consider overriding the setValue() of the picker and apply your converter there
Below is only valid for Ext.field.Date
(My first but wrong answer for a datepicker)
I recommend you to use the ISO 8601 date format for your dates. With that you need to set the submitFormat to c
submitFormat: 'c'
Tools like Newtonsoft.Json support the ISO 8601 date out of the box (and since .Net 4.5 release 1 as default).

How to serialize a JObject without the formatting?

I have a JObject (I'm using Json.Net) that I constructed with LINQ to JSON (also provided by the same library). When I call the ToString() method on the JObject, it outputs the results as formatted JSON.
How do I set the formatting to "none" for this?
Call JObject's ToString(Formatting.None) method.
Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.
Documentation: Write JSON text with JToken.ToString
You can also do the following;
string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);
you can use JsonConvert.SerializeObject()
JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method
JsonConvert.SerializeObject()
JObject.Parse()