当前位置:网站首页>Cache é JSON uses JSON adapters
Cache é JSON uses JSON adapters
2022-07-04 19:02:00 【User 7741497】
JSON An adapter is a device that will ObjectScript object (registered, serial or persistent) Mapping to JSON Methods of text or dynamic entities . This chapter covers the following topics :
- Export and import - Introduction enabling
JSONAnd demonstrate%JSON.AdaptorImport and export methods - With parameter mapping - Describes how to control how object attributes are converted to
JSONAttribute parameters of the field . - Use extended data mapping blocks - Describes how to apply multiple parameter mappings to a single class .
- format
JSON- Show me how to use%JSON.ForMatterformatJSONcharacter string . %JSONquick reference - Provide each of the... Discussed in this chapter%JSONA brief description of class members .
Exporting and Importing
from JSON Serialize or serialize to JSON Any class of requires subclasses %JSON.Adaptor, It includes the following methods :
%JSONExport()Will enable JSON The class of is serialized as JSON file , And write it to the current device .%JSONExportToStream()Will enable JSON The class of is serialized as JSON Document and write it to the stream .%JSONExportToString()Will enable JSON The class of is serialized as JSON Document and return it as a string .%JSONImport()take JSON Import as string or stream , Or as%DynamicAbstractObject Subclass import of , And return to enable JSON Instance of class for .
To demonstrate these methods , The examples in this section will use these two classes :
Enable JSON Class Model.Event and Model.Location
Class Model.Event Extends (%Persistent, %JSON.Adaptor)
{
Property Name As %String;
Property Location As Model.Location;
} Class Model.Location Extends (%Persistent, %JSON.Adaptor)
{
Property City As %String;
Property Country As %String;
} As you can see , We have a lasting Event class , There is one Location The attribute type is Model.Location. Both classes inherit from %JSON.Adaptor. This enables you to populate the object graph , And export it directly as JSON character string .
Export objects as JSON character string
/// d ##class(PHA.TEST.Xml).SaveEvent()
ClassMethod SaveEvent()
{
set event = ##class(Model.Event).%New()
set event.Name = "Global Summit"
set location = ##class(Model.Location).%New()
set location.Country = "United States of America"
set event.Location = location
do event.%JSONExport()
}This code shows the following JSON character string :
DHC-APP>d ##class(PHA.TEST.Xml).SaveEvent()
{"Name":"Global Summit","Location":{"Country":"United States of America"}} have access to %JSONExportToString() instead of %JSONExport() take JSON Assign a string to a variable :
/// d ##class(PHA.TEST.Xml).SaveEventString()
ClassMethod SaveEventString()
{
set event = ##class(Model.Event).%New()
set event.Name = "Global Summit"
set location = ##class(Model.Location).%New()
set location.Country = "United States of America"
set event.Location = location
do event.%JSONExportToString(.jsonEvent)
w jsonEvent,!
}DHC-APP>d ##class(PHA.TEST.Xml).SaveEventString()
{"Name":"Global Summit","Location":{"Country":"United States of America"}} Last , Can pass %JSONImport() take JSON String conversion back to object . This example gets the string variable from the previous example jsonEvent, And convert it back to Model.Event object :
take JSON Import strings into objects
/// d ##class(PHA.TEST.Xml).SaveEventStringImport()
ClassMethod SaveEventStringImport()
{
set event = ##class(Model.Event).%New()
set event.Name = "yx"
set location = ##class(Model.Location).%New()
s location.City = "tianjin"
set location.Country = "United States of America"
set event.Location = location
do event.%JSONExportToString(.jsonEvent)
set eventTwo = ##class(Model.Event).%New()
do eventTwo.%JSONImport(jsonEvent)
write eventTwo.Name,!,eventTwo.Location.City
}DHC-APP>d ##class(PHA.TEST.Xml).SaveEventStringImport()
yx
tianjinBoth import and export are applicable to any nested structure .
Use parameter mapping
You can specify the mapping logic for each individual attribute by setting the corresponding parameters .
You can change by specifying attribute parameters Model.Event class ( Defined in the previous section ) Mapping :
Class Model.Event Extends (%Persistent, %JSON.Adaptor)
{
Property Name As %String(%JSONFIELDNAME = "eventName");
Property Location As Model.Location(%JSONINCLUDE = "INPUTONLY");
}This mapping introduces two changes :
- The attribute name will be mapped to the name
eventNameOf JSON Field . LocationProperties will still be determined by%JSONImport()As input , But will be%JSONExport()And other export methods ignore .
before , In unmodified Model.Event Called on an instance of a class %JSONExport(), And return to the following JSON character string :
{"Name":"Global Summit","Location":{"City":"Boston","Country":"United States of America"}} If you remap Model.Event The instance %JSONExport()( Use the same attribute value ), The following string will be returned :
DHC-APP>d ##class(PHA.TEST.Xml).SaveEvent()
{"eventName":"Global Summit"}There are various parameters that can be used to adjust the mapping :
%JSONFIELDNAME(Attributes only ) Set to be used as JSON The string of the field name in the content ( By default , The value is the attribute name ).%JSONIGNOREINVALIDFIELDControl of JSON Processing of unexpected fields in input .%JSONIGNORENULLAllows developers to override the default handling of empty strings for string properties .%JSONINCLUDE( Attributes only ) Specify whether the attribute is included in JSON Output or input ( Valid values are"inout"( Default ),"outputonly","inputOnly", or"none").%JSONNULLSpecifies how to store empty strings for string properties .%JSONREFERENCESpecifies how to project object references to JSON Field . Options includeOBJECT( The default value is )、ID、OIDandGUID.
Use XData Mapping block
Can be in special XData mapping Specify the mapping in the block , And apply the mapping when calling the import or export methods , Instead of setting mapping parameters at the attribute level .
Class Model.Event Extends (%Persistent, %JSON.Adaptor)
{
Property Name As %String;
Property Location As Model.Location;
XData OnlyLowercaseTopLevel
{
<Mapping xmlns="http://www.intersystems.com/jsonmapping">
<Property Name="Name" FieldName="eventName"/>
<Property Name="Location" Include="INPUTONLY"/>
</Mapping>
}
Storage Default
{
<Data name="EventDefaultData">
<Value name="1">
<Value>%%CLASSNAME</Value>
</Value>
<Value name="2">
<Value>Name</Value>
</Value>
<Value name="3">
<Value>Location</Value>
</Value>
</Data>
<DataLocation>^Model.EventD</DataLocation>
<DefaultData>EventDefaultData</DefaultData>
<IdLocation>^Model.EventD</IdLocation>
<IndexLocation>^Model.EventI</IndexLocation>
<StreamLocation>^Model.EventS</StreamLocation>
<Type>%Storage.Persistent</Type>
}
} There is an important difference :XData In the block JSON Mapping does not change the default behavior , However, you can use the optional parameters in the import and export methods %mappingName Specify block names in to apply them . for example :
do event.%JSONExport("OnlyLowercaseTopLevel")/// d ##class(PHA.TEST.Xml).SaveEventXData()
ClassMethod SaveEventXData()
{
set event = ##class(Model.Event).%New()
set event.Name = "Global Summit"
set location = ##class(Model.Location).%New()
set location.Country = "United States of America"
set event.Location = location
do event.%JSONExport("OnlyLowercaseTopLevel")
}Show
{"eventName":"Global Summit"}It's like specifying parameters in the attribute definition .
If there is no extension block with the name provided , The default mapping will be used . Using this method , You can configure multiple mappings and reference the mappings required for each call separately , So that we can better control , At the same time, it makes your mapping more flexible and reusable .
Define to extended data mapping block
Support JSON Classes of can define any number of additional mappings . Each mapping is defined in a separate extension block in the following form :
XData {MappingName}
{
<Mapping {ClassAttribute}="value" [...] xmlns="http://www.intersystems.com/jsonmapping".>
<{Property Name}="PropertyName" {PropertyAttribute}="value" [...] />
[... more Property elements]
</Mapping>
} among ,{MappingName}、{ClassAttribute}、{Property Name} and {PropertyAttribute} Is defined as follows :
MappingName%JSONREFERENCEParameter orReferenceThe name of the mapping used by the property .ClassAttributeSpecify the mapped class parameters . You can define the following class attributes :Mapping- Name of the XDATA mapping block to apply .IgnoreInvalidField- Specify class parameters%JSONIGNOREINVALIDFIELD.NULL- Specify class parameters%JSONNULL.IgnoreNull- Specify class parameters%JSONIGNORENULL.Reference- Specify class parameters%JSONREFERENCE.
PropertyNameThe name of the attribute to map .PropertyAttributeSpecify the property parameters of the mapping . You can define the following properties :FieldName- Specify attribute parameters%JSONFIELDNAME( By default, it is the same as the attribute name ).Include- Specify attribute parameters%JSONINCLUDE( Valid values are"inout"( The default value is ),"outputonly","inputOnly", or"none").Mapping- The name of the mapping definition to apply to object attributes .NULL- Override class parameters%JSONNULL.IgnoreNull- Override class parameters%JSONIGNORENULL.Reference- Override class parameters%JSONREFERENCE.
format JSON
%JSON.ForMatter Is a class with a very simple interface , Allow dynamic objects 、 Array and JSON The string is formatted into a more readable representation . All methods are instance methods , So always start by retrieving instances :
set formatter = ##class(%JSON.Formatter).%New()The reason behind this choice is , The formatter can be configured to use certain characters as line terminators and indents only once ( for example , Spaces and tabs ; See the attribute list at the end of this section ), Then use it wherever you need it .
Format() Method accepts dynamic entities or JSON character string . Here is a simple example of using dynamic objects :
/// d ##class(PHA.TEST.Xml).FormatterJson()
ClassMethod FormatterJson()
{
s formatter = ##class(%JSON.Formatter).%New()
s dynObj = {"type":"string"}
do formatter.Format(dynObj)
}DHC-APP>d ##class(PHA.TEST.Xml).FormatterJson()
{
"type":"string"
}Format Method can direct the output to the current device 、 String or stream :
Format()Format with the specified indentation JSON Document and write it to the current device .FormatToStream()Format with the specified indentation JSON Document and write it to the stream .FormatToString()Format with the specified indentation JSON Document and write it to the string , Or will enable JSON The class of is serialized as JSON Document and return it as a string .
Besides , The following properties can be used to control indents and line breaks :
IndentIndent specifies whether to indent JSON OutputIndentCharsSpecify the character sequence for each indentation level ( The default is one space for each level ).LineTerminatorLine terminator specifies that the character sequence of each line is terminated when indenting .
边栏推荐
猜你喜欢

Li Kou brush question diary /day6/6.28

Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology

Halcon模板匹配

Thawte通配符SSL证书提供的类型有哪些

Torchdrug tutorial

VMware Tools和open-vm-tools的安装与使用:解决虚拟机不全屏和无法传输文件的问题

Installation and use of VMware Tools and open VM tools: solve the problems of incomplete screen and unable to transfer files of virtual machines

Principle and application of ThreadLocal

爬虫(6) - 网页数据解析(2) | BeautifulSoup4在爬虫中的使用

小发猫物联网平台搭建与应用模型
随机推荐
MXNet对GoogLeNet的实现(并行连结网络)
Improve the accuracy of 3D reconstruction of complex scenes | segmentation of UAV Remote Sensing Images Based on paddleseg
Using FTP
完善的js事件委托
力扣刷题日记/day3/2022.6.25
Li Kou brush question diary /day1/2022.6.23
Scala基础教程--20--Akka
Learning path PHP -- phpstudy "hosts file does not exist or is blocked from opening" when creating the project
How to improve development quality
物联网应用技术的就业前景和现状
Journal des problèmes de brosse à boutons de force / day6 / 6.28
6.26CF模拟赛B:数组缩减题解
[system disk back to U disk] record the operation of system disk back to U disk
Scala basic tutorial -- 19 -- actor
Li Kou brush question diary /day8/7.1
Lua emmylua annotation details
Scala基础教程--15--递归
【Go语言刷题篇】Go完结篇|函数、结构体、接口、错误入门学习
Caché JSON 使用JSON适配器
Wanghongru research group of Institute of genomics, Chinese Academy of Agricultural Sciences is cordially invited to join