当前位置:网站首页>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 .
边栏推荐
猜你喜欢
How to modify icons in VBS or VBE
ByteDance dev better technology salon was successfully held, and we joined hands with Huatai to share our experience in improving the efficiency of web research and development
Halcon模板匹配
一、C语言入门基础
力扣刷题日记/day4/6.26
An example of multi module collaboration based on NCF
提升复杂场景三维重建精度 | 基于PaddleSeg分割无人机遥感影像
Machine learning concept drift detection method (Apria)
基于lex和yacc的词法分析器+语法分析器
力扣刷题日记/day5/2022.6.27
随机推荐
[209] go language learning ideas
神经网络物联网是什么意思通俗的解释
信息学奥赛一本通 1336:【例3-1】找树根和孩子
【OpenCV入门到精通之九】OpenCV之视频截取、图片与视频互转
力扣刷題日記/day6/6.28
DeFi生态NFT流动性挖矿系统开发搭建
Torchdrug tutorial
Learning path PHP -- phpstudy "hosts file does not exist or is blocked from opening" when creating the project
Scala基础教程--14--隐式转换
正则替换【JS,正则表达式】
C language printing exercise
NBA赛事直播超清画质背后:阿里云视频云「窄带高清2.0」技术深度解读
6.26CF模拟赛B:数组缩减题解
基于NCF的多模块协同实例
【机器学习的数学基础】(一)线性代数(Linear Algebra)(上+)
【Go语言刷题篇】Go完结篇|函数、结构体、接口、错误入门学习
Imitation of numpy 2
How to download files using WGet and curl
My colleagues quietly told me that flying Book notification can still play like this
Improve the accuracy of 3D reconstruction of complex scenes | segmentation of UAV Remote Sensing Images Based on paddleseg