问题描述
我需要编写一些代码来从我的应用程序将从网站接收的JSON字符串中检索数据。
I need to write some code to retrieve data from a JSON string that my application will receive from a web site.
这是JSON字符串。
This is the JSON string.
{
"client" :
{
"Name" : "john doe",
"Phone" : 12345678,
"Address": "5th av",
},
"order" : [
{
"Code" : 101,
"Quantity" : 1,
"Cost": 10.50,
"Coment" : ""
},
{
"Code" : 102,
"Quantity" : 3,
"Cost": 8.50,
"Coment" : ""
},
{
"Code" : 103,
"Quantity" : 1,
"Cost": 21.50,
"Coment" : ""
}
]
}
我对如何读取对和数组感到非常困惑。我已经尝试过在此处和其他论坛上发布的许多代码,但仍然无法完成。
I am getting very confused about how to read pairs and arrays. I've tried lots of code posted here and other forums, but I still cannot get it done.
有人可以给我一些提示来完成它吗?我正在使用XE5和JSON单元。
Can anyone give me some hints to get it done? I am using XE5 and JSON units.
推荐答案
我不会为您编写实际的代码,但是我要提示。
I'm not going to write the actual code for you, but I am going to give you a hint.
这是显示的JSON结构:
Here is the structure of the JSON you have shown:
object
|
|_ client (object)
| |_ Name (string)
| |_ Phone (string)
| |_ Address (string)
|
|_ order (array)
|_ [0] (object)
| |_ Code (number)
| |_ Quantity (number)
| |_ Code (number)
| |_ Coment (string)
|
|_ [1] (object)
| |_ Code (number)
| |_ Quantity (number)
| |_ Code (number)
| |_ Coment (string)
|
|_ [2] (object)
|_ Code (number)
|_ Quantity (number)
|_ Code (number)
|_ Coment (string)
您可以将 Data.DBXJSON
单元(它们已移至单元)。
You can map that 1-to-1 to Delphi's native JSON classes in the Data.DBXJSON
unit (they were moved to the System.JSON
unit in XE6).
- 首先将JSON字符串传递给,它返回。将该类型键入到。
- 使用其属性可访问
客户端
和订单
值。将它们键入到TJSONObject
和。 - 对于
客户端
对象,请使用其Values
属性访问Name
,Phone
和Address
值。您可以调用其方法获取其字符串值。 - 对于
order
数组,使用其和属性,或其方法(间接在,以遍历数组项,然后将每个项键入到TJSONObject
中进行访问其Values
属性。数字值,将它们键入到访问其,和属性。
- Start by passing the JSON string to
TJSONObject.ParseJSONValue()
, which returns aTJSONValue
. Type-cast that to aTJSONObject
. - Use its
Values
property to access theclient
andorder
values. Type-cast them toTJSONObject
andTJSONArray
, respectively. - For the
client
object, use itsValues
property to access theName
,Phone
, andAddress
values. You can call theirValue()
method to get their string values. - for the
order
array, use itsCount
andItems
properties, or itsGetEnumerator
method (indirectly in afor..in
loop, to iterate through the array items. Type-cast each one to aTJSONObject
to access itsValues
property. For the number values, type-cast them toTJSONNumber
to access theirAsInt
,AsInt64
, andAsDouble
properties as needed.
有关更多信息,请参见Embarcadero的。
See Embarcadero's JSON documentation for more information.
这篇关于Delphi从JSON对象访问数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!