2014-09-01 144 views
0

我正在開發一個iOS應用程序,它使用用java編寫的Web服務。 該應用程序進行POST請求,該Web服務器發送一個NSData對象,從JSON創建的,這是例如:將NSData轉換爲Java字符串

<7b22636c 69656e74 223a7b22 656e7669 726f6e6d 656e7422 3a227361 6e64626f 78222c22 70726f64 7563745f 6e616d65 223a2250 61795061 6c20694f 53205344 4b222c22 70617970 616c5f73 646b5f76 65727369 6f6e223a 22322e32 2e31222c 22706c61 74666f72 6d223a22 694f5322 7d2c2272 6573706f 6e73655f 74797065 223a2270 61796d65 6e74222c 22726573 706f6e73 65223a7b 22696422 3a225041 592d3233 44393230 32375545 36383337 3034304b 51434337 5859222c 22737461 7465223a 22617070 726f7665 64222c22 63726561 74655f74 696d6522 3a223230 31342d30 392d3031 5430383a 33353a34 335a222c 22696e74 656e7422 3a227361 6c65227d 7d> 

所以在我的servlet我做

String req = request.getParameter("data"); 

但很明顯,當我嘗試打印它我得到上面的字節。

如何將這些數據轉換爲初始JSON?

編輯1: 我這樣

NSData *confirmation = [NSJSONSerialization dataWithJSONObject:completedPayment.confirmation 
                  options:0 
                  error:nil]; 

    NSURL *url = [NSURL URLWithString:@"MY_WS"]; 

    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url]; 
    NSString *messageBody = [NSString stringWithFormat:@"data=%@", confirmation]; 
    [theRequest setHTTPMethod:@"POST"]; 
    [theRequest setHTTPBody:[messageBody dataUsingEncoding:NSUTF8StringEncoding]]; 
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

我想我不能直接將JSON字符串發送一個NSData ...

+1

你爲什麼不送JSON? – Jens 2014-09-01 09:05:44

+0

看到這個:http://stackoverflow.com/questions/3774872/nsdata-to-java-string – 2014-09-01 09:07:33

+0

@Yasika這不是我所需要的。我已經有了字符串表單。我需要的是在包含JSON的字符串中轉換包含字節的字符串! – dylaniato 2014-09-01 09:10:42

回答

1

不確定NSData的,但如果你能得到的byte []數組,你可以將它傳遞給sting構造函數。

String javaStringRep = new String(theByteArray, "UTF-8"); 

希望這有助於.. :)