Swift - JSON数组值

时间:2017-08-14 16:40:13

标签: json swift

我在输出中获得了以下JSON值:

[["category_title": Shelly], ["category_title": Thaddeus],
["category_title": Chantale], ["category_title": Adara],
["category_title": Mariko], ["category_title": Felicia]]

但我想要它如下:

["Shelly","Thaddeus","Chantale", "Adara","Mariko","Felicia"]

我有以下Swift代码。请帮助我获得以上输出。

func successGetTermsData(response: Any){
    var UserRole : String = ""
    var arrayOfDetails = response as? [[String: Any]] ?? []

    UserRole = arrayOfDetails as? String ?? ""
    print(arrayOfDetails)
}

2 个答案:

答案 0 :(得分:0)

您必须map Dictionary arrayOfDetails数组StringflatMap数组。 if let arrayOfDetails = response as? [[String: String]] { let userRole = arrayOfDetails.flatMap { $0["category_title"] } print(userRole) } 忽略了丢失的密钥。

cameraObject.setPreviewCallback(new Camera.PreviewCallback(){
     @Override
     public void onPreviewFrame(byte[] data, Camera camera) {

            try {

                if (cameraObject.getParameters().getPreviewFormat() == ImageFormat.NV21) {
                    timestampBeforecompression = SystemClock.uptimeMillis();
                    yuvImage = new YuvImage(data, imageFormat, width, height, null);
                    yuvImage.compressToJpeg(rect, 75, mByteArrayOutputStream);

                    frameToStream = mByteArrayOutputStream.toByteArray();

                    bitmap = BitmapFactory.decodeByteArray(frameToStream, 0, frameToStream.length);
                    mByteArrayOutputStream.reset();
                    bitmap = Bitmap.createScaledBitmap(bitmap, 320, 240, true);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 60, mByteArrayOutputStream);
                    frameToStream = null;
                    frameToStream = mByteArrayOutputStream.toByteArray();

                    compressionMillis = SystemClock.uptimeMillis() - timestampBeforecompression;
                    if (125 - compressionMillis > 0) {
                        SystemClock.sleep(125 - compressionMillis);
                    }

                    if (mJpegStream != null) {
                        mJpegStream.streamJpeg(frameToStream, frameToStream.length, Long.MIN_VALUE);
                    }

                    if (mByteArrayOutputStream != null) {
                        mByteArrayOutputStream.reset();
                    }

                    frameToStream = null;
               }

           } catch (Exception e) {
                System.out.println("Oops: " + e.getMessage());
           }

      }
});

答案 1 :(得分:0)

有很多方法可以做到这一点。一种方法是使用flatmap来获取字典数组中的值:

let arrayOfValues = arrayOfDetails.flatMap { $0.values }

为了使其工作,名称需要在双引号内:“Shelly”等。