0

我在访问 JSON 代码中的某个属性(hlink)时遇到问题。这是因为 JSON 输出的结构并不总是相同,因此我得到以下错误:“不能使用 stdClass 类型的对象作为数组...”。有人可以帮我解决这个问题吗?

JSON 输出 1(数组)

Array ( 
    [0] => stdClass Object ( 
    [hlink] => http://www.rock-zottegem.be/ 
    [main] => true 
    [mediatype] => webresource ) 
    [1] => stdClass Object ( 
    [copyright] => Rock Zottegem 
    [creationdate] => 20/03/2013 14:35:57 
    [filename] => b014933c-fdfd-4d93-939b-ac7adf3a20a3.jpg 
    [filetype] => jpeg 
    [hlink] => http://media.uitdatabank.be/20130320/b014933c-fdfd-4d93-939b-ac7adf3a20a3.jpg
)   

JSON 输出 2

stdClass Object ( 
    [copyright] => Beschrijving niet beschikbaar 
    [creationdate] => 24/04/2013 19:22:47 
    [filename] => Cinematek_F14281_1.jpg 
    [filetype] => jpeg 
    [hlink] => http://media.uitdatabank.be/20130424/Cinematek_F14281_1.jpg 
    [main] => true 
    [mediatype] => photo 
) 

这是我的代码:

try {
    if (!empty($img[1]->hlink)){
        echo "<img src=" . $img[1]->hlink . "?maxheight=300></img>";
    }
}
catch (Exception $e){
    $e->getMessage();
}
4

2 回答 2

0

假设这是 PHP,并且您知道 JSON 始终包含一个对象或一组对象,那么问题归结为检测您收到了哪些。

尝试类似:

if (is_array($img)) {
    $hlink = $img[0]->hlink;
} else {
    $hlink = $img->hlink;
}
于 2013-05-30T22:34:26.177 回答
0

这不是直接回答您的问题,但它应该为您提供调查您遇到的问题的方法。

代码示例

var obj1 = [ new Date(), new Date() ];
var obj2 = new Date();
obj3 = "bad";
function whatIsIt(obj) {
    if (Array.isArray(obj)) {
        console.log("obj has " + obj.length + " elements");
    } else if (obj instanceof Date) {
        console.log(obj.getTime());
    } else {
        console.warn("unexpected object of type " + typeof obj);
    }
}
// Use objects
whatIsIt(obj1);
whatIsIt(obj2);
whatIsIt(obj3);
// Serialize objects as strings
var obj1JSON = JSON.stringify(obj1);
// Notice how the Date object gets stringified to a string
// which no longer parses back to a Date object.
// This is because the Date object can be fully represented as a sting.
var obj2JSON = JSON.stringify(obj2);
var obj3JSON = JSON.stringify(obj3);
// Parse strings back, possibly into JS objects
whatIsIt(JSON.parse(obj1JSON));
// This one became a string above and stays one
// unless you construct a new Date from the string.
whatIsIt(JSON.parse(obj2JSON));
whatIsIt(JSON.parse(obj3JSON));

输出

obj has 2 elements JsonExample:6
1369955261466 JsonExample:8
unexpected object of type string JsonExample:10
obj has 2 elements JsonExample:6
unexpected object of type string JsonExample:10
unexpected object of type string JsonExample:10
undefined
于 2013-05-30T23:05:53.450 回答