2016-08-03 67 views
2

我有以下JSON結構:訪問內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

是它不只是json_s:= concurrent.Get(「身份證」)作爲TJSONString – Dsm

+0

,會給你的第一個「ID 「字段,而不是下面的」併發「字段。它部署的JSON很差,但我必須處理它。 –

+1

遍歷數組,直到找到想要的項目,然後讀取該對象。 –

回答

6

您可以像訪問其他JSON對象一樣訪問concurrent的項目。

你只需要先獲得JSON對象。但這很容易:

concurrent_sub:= concurrent.Get('concurrent').JsonValue as TJSONObject; 
json_s := concurrent_sub.Get('id').JsonValue as TJSONString; 
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']); 
+0

爲什麼downvote?這個問題沒有要求使用'System.Json'的解決方案,是嗎? –

+0

只是一個迷信,它最近成爲習慣的事情:-) –

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']

SuperObject parsing

使用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)零。

這種快速分析語法也failes使用JSON的但不JavaScript的有效載荷:https://github.com/hgourvest/superobject/issues/8