我有以下JSON结构:
concurrence: [
{
id: "481-13",
price: "11.5",
concurrent: {
id: 13,
name: "NAME1",
price: "11.5"
}
},
{
id: "481-14",
price: "12.25",
concurrent: {
id: 14,
name: "NAME2",
price: "12.25"
}
}
]
如何获得concurrent.id
值?我尝试使用RADStudio文档中列出的FindValue()
方法,但它不存在(至少在10.1柏林)。
我正在访问并发数组,如下所示:
concurrents := product.Get('concurrence').JSONValue as TJSONArray;
for j := 0 to concurrents.Size-1 do
begin
concurrent := concurrents.Get(j) as TJSONObject;
json_s := concurrent.Get('id').JsonValue as TJSONString;
my_id := json_s.Value;
json_s := concurrent.Get('price').JsonValue as TJSONString;
my_price := json_s.Value;
json_s := concurrent.FindValue('concurrent.id') as TJSONString;//NOT WORKING
my_concurrent_id := json_s.Value;
end;
是否有其他方法可以访问内部concurrent
值?
答案 0 :(得分:6)
您可以像访问每个其他JSON对象一样访问concurrent
项。
您必须先获取JSON对象。但这很容易:
concurrent_sub:= concurrent.Get('concurrent').JsonValue as TJSONObject;
json_s := concurrent_sub.Get('id').JsonValue as TJSONString;
答案 1 :(得分:1)
就个人而言,我宁愿使用JsonDataObjects。
然后代码看起来像这样:
var
product: TJsonObject;
concurrents: TJsonArray;
o: TJsonObject;
begin
...
concurrents := product.A['concurrence'];
for o in concurrents do
Writeln(o.O['concurrent'].I['id']);
答案 2 :(得分:1)
根据http://www.jsoneditoronline.org/,您的JSON格式不正确。
需要将正确的一个放入大括号中:
{
concurrence: [
{
id: "481-13",
price: "11.5",
concurrent: {
id: 13,
name: "NAME1",
price: "11.5"
}
},
{
id: "481-14",
price: "12.25",
concurrent: {
id: 14,
name: "NAME2",
price: "12.25"
}
}
]
}
通过此修正,您只需将其设为JsonVar['concurrence[0].concurrent.id']
和JsonVar['concurrence[1].concurrent.id']
使用https://github.com/hgourvest/superobject
var
obj, id: ISuperObject;
N, M: Integer;
begin
obj := SO('{ concurrence: [ { id: ....... ');
id := obj[ 'concurrence[0].concurrent.id' ];
if id <> nil then
N := id.AsInteger; // N <== 13
M := obj.I[ 'concurrence[1].concurrent.id' ]; // M <== 14
obj := nil;
id := nil;
end;
后一种选择虽然更容易但有点片状。
由于它无法返回nil
,因此在找不到实际值时会返回default(Integer)
。
这种快速解析语法也会使用JSON-but-not-JavaScript有效负载:https://github.com/hgourvest/superobject/issues/8