1

作为 HTTP 请求的结果,我在 URLLoader 对象中获得了 JSON 数据。我需要将 JSON 以格式化的方式放入 TextField 中。

我怎样才能做到这一点:

[{"id":"barrrrrr","client":"foo"}]

看起来像这样:

[
   {
      "id":"barrrrrr",
      "client":"foo"
   }
]

在文本字段内?

干杯。

4

2 回答 2

3

在 flash player 11+ 中使用本机 JSON 对象

var stringJSON:String = loader.data as String;
var jsonData:Object = JSON.parse(stringJSON);
textField.text = JSON.stringify(jsonData,null,4);
于 2012-11-02T17:42:48.070 回答
0

这与您所要求的不完全相同,但我们使用此方法记录 as3 对象(也是 json),它可能对您也有用:

package
{
import flash.display.Sprite;
import flash.utils.getQualifiedClassName;

public class astest extends Sprite
{
    public function astest()
    {
        var jsonStr:String = '[{"id":"barrrrrr","client":{"id":"barrrrrr","client":"foo"}},{"id":"barrrrrr","client":"foo"}]';
        var jsonObj:Object = JSON.parse(jsonStr);

        trace(parse(jsonObj));
    }

    private static const simpleTypes:Array = ["int", "uint", "String", "Number", "Boolean", "null", "XML", "void"];
    private static function parse(o:Object, tabs:String = ""):String
    {
        var out:String = "";
        var tabStr:String = "    ";
        var cnt:int = 40;           //number of properties on the same object to log out 
        var type:String;

        for(var prop:* in o)
        {
            type = "null";
            try{
                type = getQualifiedClassName(o[prop]);
            }catch(error:Error){};

            out+= tabs + String(prop) + ":" + type + " = ";

            if(simpleTypes.indexOf(type) >=0)
                out+=o[prop]+"\r";
            else
                out+=type+"\r"+parse(o[prop], tabs+tabStr);

            if(--cnt<=0)
            {
                out+=tabs+"...\r";
                break;
            }
        }

        return out;
    }
}
}

此示例的输出将是:

0:Object = Object
    client:Object = Object
        client:String = foo
        id:String = barrrrrr
    id:String = barrrrrr
1:Object = Object
    client:String = foo
    id:String = barrrrrr

您可以修改parse方法(这很简单)以使输出与您的更相似。

于 2012-11-02T14:36:43.267 回答