当前位置:网站首页>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
JSON
And demonstrate%JSON.Adaptor
Import and export methods - With parameter mapping - Describes how to control how object attributes are converted to
JSON
Attribute 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.ForMatter
formatJSON
character string . %JSON
quick reference - Provide each of the... Discussed in this chapter%JSON
A 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%DynamicAbstract
Object 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
tianjin
Both 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
eventName
Of JSON Field . Location
Properties 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 ).%JSONIGNOREINVALIDFIELD
Control of JSON Processing of unexpected fields in input .%JSONIGNORENULL
Allows 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"
).%JSONNULL
Specifies how to store empty strings for string properties .%JSONREFERENCE
Specifies how to project object references to JSON Field . Options includeOBJECT( The default value is )
、ID
、OID
andGUID
.
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
%JSONREFERENCE
Parameter orReference
The name of the mapping used by the property .ClassAttribute
Specify 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
.
PropertyName
The name of the attribute to map .PropertyAttribute
Specify 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 :
Indent
Indent specifies whether to indent JSON OutputIndentChars
Specify the character sequence for each indentation level ( The default is one space for each level ).LineTerminator
Line terminator specifies that the character sequence of each line is terminated when indenting .
边栏推荐
猜你喜欢
Principle and application of ThreadLocal
How is the entered query SQL statement executed?
Journal des problèmes de brosse à boutons de force / day6 / 6.28
神经网络物联网平台搭建(物联网平台搭建实战教程)
An example of multi module collaboration based on NCF
【2022年江西省研究生数学建模】水汽过饱和的核化除霾 思路分析及代码实现
[go ~ 0 to 1] read, write and create files on the sixth day
Nature microbiology | viral genomes in six deep-sea sediments that can infect Archaea asgardii
Wanghongru research group of Institute of genomics, Chinese Academy of Agricultural Sciences is cordially invited to join
Installation and use of VMware Tools and open VM tools: solve the problems of incomplete screen and unable to transfer files of virtual machines
随机推荐
Li Kou brush question diary /day6/6.28
Scala basic tutorial -- 15 -- recursion
力扣刷题日记/day3/2022.6.25
中国农科院基因组所汪鸿儒课题组诚邀加入
【Go语言刷题篇】Go完结篇|函数、结构体、接口、错误入门学习
Scala基础教程--14--隐式转换
[cloud voice suggestion collection] cloud store renewal and upgrading: provide effective suggestions, win a large number of code beans, Huawei AI speaker 2!
Li Kou brush question diary /day8/7.1
How to modify icons in VBS or VBE
Thawte通配符SSL证书提供的类型有哪些
Learning path PHP -- phpstudy "hosts file does not exist or is blocked from opening" when creating the project
Principle and application of ThreadLocal
[209] go language learning ideas
2022年字节跳动日常实习面经(抖音)
I always thought that excel and PPT could only be used for making statements until I saw this set of templates (attached)
力扣刷题日记/day8/7.1
Digital "new" operation and maintenance of energy industry
vbs或vbe如何修改图标
Angry bird design based on unity
其他InterSystems %Net工具