delphi 实体类 与JSON转换,序列化
TJson.ObjectToJsonString
TJsonReader\TJsonTextWriter
uses System.JSON.Readers,System.JSON.Writers
http://docwiki.embarcadero.com/Libraries/Seattle/en/System.JSON.Readers
http://docwiki.embarcadero.com/Libraries/Seattle/en/System.JSON.Writers
http://docwiki.embarcadero.com/Libraries/Seattle/en/System.JSON.Readers.TJsonReader
http://docwiki.embarcadero.com/Libraries/Seattle/en/System.JSON.Writers.TJsonTextWriter
unit CollectionObjects;
interface
type
TPerson = class private FAge: Integer; FLastName: string; FFirstName: string; public constructor Create(const FirstName, LastName: String; Age: Integer); property FirstName: string read FFirstName write FFirstName; property LastName: string read FLastName write FLastName; property Age: Integer read FAge write FAge; end; implementation { TPerson } constructor TPerson.Create(const FirstName, LastName: String; Age: Integer); begin FFirstName := FirstName; FLastName := LastName; FAge := Age; end;
fMyPeople: TObjectList; fMyPeople := TObjectList .Create(True); // The individual TPerson objects fMyPeople.Add(TPerson.Create('Gomez', 'Addams', 40)); fMyPeople.Add(TPerson.Create('Morticia', 'Addams', 38)); fMyPeople.Add(TPerson.Create('Pugsley', 'Addams', 8)); fMyPeople.Add(TPerson.Create('Wednesday', 'Addams', 12)); // Use TObjectBindSourceAdapter for a single object ABindSourceAdapter := TListBindSourceAdapter .Create(Self, FMyPeople, True); function PrettyJSON(AJson: String): String; begin Result := StringReplace(AJson, '},', '},' + sLineBreak, [rfReplaceAll]); Result := StringReplace(Result, '[{', '[' + sLineBreak + '{', [rfReplaceAll]); end; procedure TABSMainForm.JsonToObjects; var NewPeople: TObjectList ; begin NewPeople := TJson.JsonToObject >(Memo1.Text); fMyPeople.Clear; fMyPeople.AddRange(NewPeople.ToArray); end; procedure TABSMainForm.ObjectsToJson; begin Memo1.Text := PrettyJSON(TJson.ObjectToJsonString(fMyPeople)); end;
JsonToObject
ObjectToJsonString
JSON字符串转换为对象
{"ownsObjects":true,"listHelper":[9],"items":[
{"age":40,"lastName":"Addams","firstName":"Gomez"},
{"age":38,"lastName":"Addams","firstName":"Morticia"},
{"age":8,"lastName":"Addams","firstName":"Pugsley"},
{"age":12,"lastName":"Addams","firstName":"Wednesday"},
{"age":55,"lastName":"Fester","firstName":"Uncle"},
{"age":72,"lastName":"Frump","firstName":"Grandmama"},
{"age":50,"lastName":"Lurch","firstName":""},
{"age":99,"lastName":"Thing","firstName":"Thing T."},
{"age":21,"lastName":"Itt","firstName":"Cousin"},
null,null,null,null,null,null,null]}
TJson::ObjectToJsonString();
数据集转为Json
DataSetConverter4Delphi
https://github.com/ezequieljuliano/DataSetConverter4Delphi
Object>JsonString 类对象序列化为json字符串。
TPerson=class()....
string astr:= TJson.ObjectToJsonString(person);
JsonString反序列化 实例化为类对象
person := TJson.JsonToObject
Tokyo 10.2新增类,效率更高更快。
TJsonSerializer
Serializer:=TJsonSerializer.Create
String astr=Serializer.Serialize
person= nSeriallizer.Deserialize
感觉TJsonSerializer与.net的开源Newtonsoft.Json类似,功能基本相同了。
TJsonSerializer在c++builder的应用
https://community.embarcadero.com/blogs/entry/10-2-tokyo-tjsonserializer-and-json-converters
First declare with Pascal to use the converter and generics. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 //// unit Unit2; interface uses System.JSON.Converters, System.JSON.Serializers, System.Generics.Collections; type TListString = TList<String>; TDictionaryStrStr = class(TDictionary<String, String>) constructor Create; overload; end; TTJsonListConverterString = TJsonListConverter<String>; TJsonDictionaryConverterStrStr = class(TJsonStringDictionaryConverter<String>) end; This is because the use of generics in C++Builder. C++Builder used Win64. 1 2 3 4 5 6 //// #include <System.JSON.Converters.hpp> #include <System.JSON.Serializers.hpp> #include <System.Generics.Collections.hpp> #include <System.JSON.Writers.hpp> #include <memory>
//// template <typename T1, typename T2> struct jCollections { UnicodeString _property_name{L""}; std::unique_ptr<TStringWriter> _string_write{std::make_unique<TStringWriter>()}; std::unique_ptr<TJsonSerializer> _j_serializer{std::make_unique<TJsonSerializer>()}; std::unique_ptr<TJsonTextWriter> _json_writer{std::make_unique<TJsonTextWriter>(_string_write.get())}; jCollections(UnicodeString lname) { ///Constructor. ///Determine the property name. _property_name = lname; } String listtoj(T1 l_list) { ///Start of object and setting property name. _json_writer->WriteStartObject(); _json_writer->WritePropertyName(_property_name); ///TJsonListConverter__1 or TJsonDictionaryConverterStrStr. std::unique_ptr<T2 > l_json_conv{std::make_unique<T2 >()}; ///Here convert the value of the input list. l_json_conv->WriteJson(_json_writer.get(), TValue::_op_Implicit(l_list), _j_serializer.get()); _json_writer->WriteEndObject(); ///returns a string. return _string_write->ToString(); } }; void __fastcall TForm1::Button1Click(TObject *Sender) { TList__1<String>* l_list= new TList__1<String>(); try { jCollections<TList__1<String>*, TJsonListConverter__1<String> > _jCollections{L"language_List"}; l_list->Add("Python"); l_list->Add("Delphi"); l_list->Add("C++"); l_list->Add("JAVA"); l_list->Add("ひまわり"); Memo1->Lines->Append(_jCollections.listtoj(l_list) ); } __finally { delete l_list; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button2Click(TObject *Sender) { TDictionaryStrStr* l_dic = new TDictionaryStrStr(); try { jCollections<TDictionaryStrStr*, TJsonDictionaryConverterStrStr > _jCollections{L"2017_MotoGP_standings"}; l_dic->Add("Maverick Vinales", "Movistar Yamaha"); l_dic->Add("Andrea Dovizioso", "Ducati"); l_dic->Add("Valentino Rossi", "Movistar Yamaha"); l_dic->Add("Marc Marquez", "Repsol Honda Team"); l_dic->Add("Dani Pedrosa", "Repsol Honda Team"); Memo1->Lines->Append(_jCollections.listtoj(l_dic)); } __finally { delete l_dic; } }
Button1 is TList<String> to JSON Convert. Button2 is TDictionary<String, String>to JSON.
3.数组json
TUser = class public FAge: Integer; FLastName: string; FFirstName: string; end;
TJsonSerializer的序列化操作,class和 record都支持,使用起来太方便了。
数组2json
procedure TForm3.Button14Click(Sender: TObject); var user: TUser; userList: TArray; begin user := TUser.Create; user.FAge := 1; user.FFirstName := 'delphi'; user.FLastName := 'berlin'; SetLength(userList, 2); userList[0] := user; user := TUser.Create; user.FFirstName := 'delphi'; user.FAge := 2; user.FLastName := 'tokyo'; userList[1] := (user); self.Memo1.Text := TJsonSerializer.Create.Serialize(userList); end;
json2数组
procedure TForm3.Button15Click(Sender: TObject); var userList: TArray; user: TUser; i: TArray ; begin userList := TJsonSerializer.Create.Deserialize < TArray < TUser >> (Memo1.Text); Memo2.Clear; for user in userList do begin Memo2.Lines.Add(user.FAge.ToString); Memo2.Lines.Add(user.FFirstName); Memo2.Lines.Add(user.FLastName); end; end;