2016-12-08 39 views
0

我想使用Alamofire(V3.5.1),並且我正在使用Swift(V2.3)。我想發佈的JSON是這個。如何使用Alamofire發佈嵌套的JSON?

{ 
    "inputs": [ 
    { 
     "image": { 
     "dataType": 50, 
     "dataValue": "base64_image_string" 
     }, 
     "configure": { 
     "dataType": 50, 
     "dataValue": "{\"side\":\"face\"}" 
     } 
    } 
    ] 
} 

我儘量讓Alamofire參數,這樣

let parameters : [String: AnyObject] = [ 
     "inputs" : [ 
     [ "image":[ 
      "dataType":50, 
      "dataValue":(base64String) 
      ], 
      "configure":[ 
      "dataTpye":50, 
       "dataValue": ["side" :"face"] 
      ] 
      ] 
     ] 
    ] 

但結果我得到的是這樣的。 FAILURE: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0.

問題1:我如何在正文中發佈正確的嵌套json?

編輯:我試圖用@Zonily Jame的方式來創建JSON對象,但它失敗了。這裏是我的代碼:

 let imageData:[String:AnyObject] = ["dataType":50, "dataValue":"string"] 
    let configureData:[String:AnyObject] = ["dataType":50, "dataValue":"{\"side\":\"face\"}"] 
    let inputsData:[String:AnyObject] = ["image":dictToJSON(imageData) , "configure":dictToJSON(configureData)] 
    let parameters:[String:AnyObject] = ["inputs":dictToJSON(inputsData)] 

,我打印的parameters變量,它是這樣的:

["inputs": { 
    configure =  { 
     dataType = 50; 
     dataValue =   { 
      side = face; 
     }; 
    }; 
    image =  { 
     dataType = 50; 
     dataValue = ""; 
    }; 
}] 

不知何故,語法仍然不正確。而且我還試圖在變量configureData上使用dictToJSON(),我仍然得到了相同的結果。


的預期反應應該是

{ 
    "outputs": [ 
    { 
     "outputLabel": "ocr_id", 
     "outputMulti": {}, 
     "outputValue": { 
     "dataType": 50, 
     "dataValue": "{\"address\": \"string\", \"config_str\" : \"{\"side\":\"face\"}\", \"name\" : \"Jack\",\"num\" : \"1234567890\", \"success\" : true}" 
     } 
    } 
    ] 
} 

編輯:這是API的有關如何短語迴應,但在JAVA

try { 
      JSONObject resultObj = new JSONObject(result); 
      JSONArray outputArray = resultObj.getJSONArray("outputs"); 
      String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); 
      JSONObject out = new JSONObject(output); 
      if (out.getBoolean("success")) { 
       String addr = out.getString("address"); 
       String name = out.getString("name"); 
       String num = out.getString("num"); 
       System.out.printf(" name : %s \n num : %s\n address : %s\n", name, num, addr); 
      } else { 
       System.out.println("predict error"); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

,並請求代碼文件

public static JSONObject getParam(int type, JSONObject dataValue) { 
     JSONObject obj = new JSONObject(); 
     try { 
      obj.put("dataType", type); 
      obj.put("dataValue", dataValue); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return obj; 
    } 


    public static JSONObject getParam(int type, String dataValue) { 
     JSONObject obj = new JSONObject(); 
     try { 
      obj.put("dataType", type); 
      obj.put("dataValue", dataValue); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return obj; 
    } 

     JSONObject requestObj = new JSONObject(); 
     try { 
      JSONObject configObj = new JSONObject(); 
      JSONObject obj = new JSONObject(); 
      JSONArray inputArray = new JSONArray(); 
      configObj.put("side", configStr); 
      obj.put("image", getParam(50, imgBase64)); 
      obj.put("configure", getParam(50, configObj.toString())); 
      inputArray.put(obj); 
      requestObj.put("inputs", inputArray); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     String body = requestObj.toString(); 

注意:imgBase64是一個字符串。

問題2:我該如何分析這種JSON?我只想要dataValue,謝謝

+0

您可以發佈您Alamofire代碼? **注:**,你可以隱藏在必要時配偶 –

+0

你得到的參數是正確的海事組織,在'api'你確定服務器是由接受申請'/ json'類型參數的網址是什麼?在「我準備得到迴應」之後,我不明白你的意思嗎? –

+0

@ZonilyJame我的意思是服務器會給我這個迴應,這是API的Document.And我使用這個Alamofire方法'Alamofire.request(.POST, url, 參數,參數, 編碼:.JSON , 標題:標題).responseJSON' – Shucheng

回答

0

你應該做的是先轉換您Dictionaries/ArraysSuper Dictionary到JSON對象中

例如讓我們做對象

let object = [ 
    "franchise": [ 
     "name": "Marvel", 
     "movies": ["Doctor Strange", "Iron Man", "Spider Man"] 
    ] 
] 

對於這個工作,我們需要對這些對象,這大致是這樣的分離(只是這樣做是爲了可讀性)

let movies:[String] = ["Doctor Strange", "Iron Man", "Spider Man"] 

let franchiseDetails:[String:AnyObject] = [ 
    "name": "Marvel", 
    "movies": movies 
] 
let franchise:[String:AnyObject] = [ 
    "franchise": franchiseDetails 
] 

然後只需將它們轉換成JSON對象通過使用NSJSONSerialization通過在Alamofire請求使用這些功能

func dictToJSON(dict:[String: AnyObject]) -> AnyObject { 
    let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted) 
    let decoded = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: []) 
    return decoded 
} 

func arrayToJSON(array:[String]) -> AnyObject { 
    let jsonData = try! NSJSONSerialization.dataWithJSONObject(array, options: .PrettyPrinted) 
    let decoded = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: []) 
    return decoded 
} 


let newObject = [ 
    "franchise": dictToJSON([ 
     "name": "Marvel", 
     "movies": arrayToJSON(["Doctor Strange", "Iron Man", "Spider Man"]) 
    ]) 
] 

現在你可以使用這個對象

+0

感謝您的回答,這非常有用。另外一個問題是如何將這個字符串添加到字典中? ''dataValue「:」{\「side \」:\「face \」}「'我很困惑。 – Shucheng

+0

這應該是字典中的字典嗎? –

+0

我不確定。這是一個API請求示例 – Shucheng

1

你可以給字典類型的嵌套字典,或者你可以爲需要字典的每個鍵製作單獨的字典。 就像[AnyObject:AnyObject]。

對於關鍵的分析,你可以轉換在字典形式的響應,並使用它的方法valueforKeyPath

+0

,但'Alamofire.request'需要一個參數爲[String:AnyObject] ,所以我不能讓我的身體成爲一個[AnyObject:AnyObject]。我知道如何分析一個普通的json,但我不知道如何分析嵌套json,比如''dataValue「:」{\「address \ 「:\」 字符串\」,\ 「config_str \」:\ 「{\」 的一面\ 「:\」 面\ 「} \」,\ 「名稱\」:\ 「傑克\」,\ 「民\」: \「1234567890 \」,\「success \」:true}「'你能幫我嗎? – Shucheng

+0

if jsonResult = response as? NSDictionary讓OrderObjectIds = jsonResult.value(forKeyPath:「result.objectId」)} – rohit

+0

在keyPath中使用「outputs.outputValue.dataValue」 – rohit