You are not logged in.
Hi,
Is there a way to prevent making classes that their object do not exists in the JSON? In my JSON input sometimes the property that is a class does not exists and JSONToObject make a class for that with empty properties, can I set it to do not make an object and just pass nil to it? or I should make a custom serializer?
Here is a sample file:
{
"ID": 1,
"Childs": [{
"ID": 11,
"Childs": [{
"ID": 111,
"Childs": [{}, {}
]
}, {
"ID": 112,
"Childs": [{}, {}
]
}
]
}, {
"ID": 12,
"Childs": [{
"ID": 121,
"Childs": [{}, {}
]
}, {
"ID": 122,
"Childs": [{}, {}
]
}
]
}
],
"Options": {
"Name": "Name1"
}
}
As you can see this is a tree but only parent has "Options" and if I write serializer like below it will make Options class for every child with empty propertises like the output, can I prevent that or I should make a custom serializer? an option would be nice.
program project1;
uses
Classes,
SysUtils,
FileUtil,
SynCommons,
mORMot;
type
TItem = class;
TItems = array of TItem;
{ TOptions }
TOptions = class(TPersistent)
private
FName: string;
published
property Name: string read FName write FName;
end;
{ TItem }
TItem = class(TSynAutoCreateFields)
private
FID: integer;
FChilds: TItems;
FOptions: TOptions;
published
property ID: integer read FID write FID;
property Childs: TItems read FChilds write FChilds;
property Options: TOptions read FOptions;
end;
procedure TestIt;
var
it: TItem;
s: RawUTF8;
begin
TJSONSerializer.RegisterObjArrayForJSON([TypeInfo(TItems), TItem]);
s := StringFromFile('test.json');
it := TItem.Create;
ObjectLoadJSON(it, s);
ObjectToJSONFile(it, 'output.json');
it.Free;
end;
begin
TestIt;
end.
And the output will be like:
{
"ID": 1,
"Childs":
[
{
"ID": 11,
"Childs":
[
{
"ID": 111,
"Childs":
[
{
"ID": 0,
"Childs": [],
"Options": {
"Name": ""
}
},
{
"ID": 0,
"Childs": [],
"Options": {
"Name": ""
}
}
],
"Options": {
"Name": ""
}
},
{
"ID": 112,
"Childs":
[
{
"ID": 0,
"Childs": [],
"Options": {
"Name": ""
}
},
{
"ID": 0,
"Childs": [],
"Options": {
"Name": ""
}
}
],
"Options": {
"Name": ""
}
}
],
"Options": {
"Name": ""
}
},
{
"ID": 12,
"Childs":
[
{
"ID": 121,
"Childs":
[
{
"ID": 0,
"Childs": [],
"Options": {
"Name": ""
}
},
{
"ID": 0,
"Childs": [],
"Options": {
"Name": ""
}
}
],
"Options": {
"Name": ""
}
},
{
"ID": 122,
"Childs":
[
{
"ID": 0,
"Childs": [],
"Options": {
"Name": ""
}
},
{
"ID": 0,
"Childs": [],
"Options": {
"Name": ""
}
}
],
"Options": {
"Name": ""
}
}
],
"Options": {
"Name": ""
}
}
],
"Options": {
"Name": "Name1"
}
}
Offline
Yes but only for parent but not all the childs, I want to only make it for parent not all childs.
Offline